react列表中,当key改变后发生的事情
Posted 该人已失联
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了react列表中,当key改变后发生的事情相关的知识,希望对你有一定的参考价值。
Main.jsx
export default class Main extends PureComponent { constructor(props) { super(props); this.state = { list: [ { key: 0, value: 1 }, { key: 1, value: 2 }, { key: 2, value: 3 } ] } this.setKey = ::this.setKey; } componentWillMount() { console.log(\'main will mount\'); } componentDidMount() { console.log(\'main did mount\'); } componentWillUpdate() { console.log(\'main will update\'); } componentDidUpdate() { console.log(\'main did update\'); } componentWillUnmount() { console.log(\'main will unmount\'); } setKey() { const { list } = this.state; this.setState({ list: Array.from(list, item => { return Object.assign(item, { key: item.key + 1 }); }) }); } render() { const { list } = this.state; return ( <div> {list.map(item => <List key={item.key} value={item.value} />)} <button onClick={this.setKey}>key</button> </div> ) } }
List.jsx
export default class List extends PureComponent { constructor(props) { super(props); } componentWillMount() { console.log(`list${this.props.value} will mount`); } componentDidMount() { console.log(`list${this.props.value} did mount`); } componentWillUpdate() { console.log(`list${this.props.value} will update`); } componentDidUpdate() { console.log(`list${this.props.value} did update`); } componentWillUnmount() { console.log(`list${this.props.value} will unmount`); } render() { const { value } = this.props; return( <div> list{value} </div> ) } }
当点击key按钮后会发生什么呢?先分析一下
以上是关于react列表中,当key改变后发生的事情的主要内容,如果未能解决你的问题,请参考以下文章