有时候会遇到props没有变化,但是,组件依然更新的问题
(return使用的是this.props.data)
我将组件return的值设置为this.state.data。
没有调用this.setState,但是componentDidUpdate依然运行了。
这说明无论值变不变化和是否重新设置(我最开始以为是props设置了同样的值也会引起update),react组件都会进行更新;
后来用到了一个钩子函数:
import React,{Component} from 'react'
import ReactDOM from 'react-dom'
import { throwStatement } from '@babel/types'
// import App from './demo2'
// import Filter from './filter'
class Item extends Component{
constructor(props){
super(props);
}
shouldComponentUpdate(nextProps, nextState){
if(this.props.data===nextProps.data){
return false
}else{
return true
}
}
componentDidMount () {
console.log(this.props.data,'mount')
}
componentDidUpdate (prevProps, prevState) {
console.log(this.props.data,'update')
}
componentWillUnmount(){
console.log(this.props.data,'unmount')
}
render () {
return (
<div>
{this.props.data}
</div>
)
}
}
class List extends Component{
constructor (props) {
super(props)
this.state = {
data : [
'a','b','c','d'
]
}
}
render () {
return (
<div>
{this.state.data.map(item =><Item key={item} data={item}/>)}
</div>
)
}
componentDidMount () {
window.list = this
}
}
ReactDOM.render(<List />, document.getElementById('root'))
使用 shouldComponentUpdate可以阻止componentDidUpdate 钩子函数的运行;
最开始list.state.data的值为['a','b','c','d']
浏览器设置:list.setState({data:['a','c','b','d','e']})
运行上面的程序只打印了 e mount;说明,组件调换了位置也不会引起重新渲染。