我有以下“列表”组件,试图从道具中更新this.state。我似乎无法使getDrivedStateFromProps与componentDidUpdate一起正常工作。逻辑上存在问题,但无论是否将其注释掉,gDSFC似乎都不会触发,因为我得到相同的响应。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>list</title>
<script src="react/react.js"></script>
<script src="react/react-dom.js"></script>
<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
</head>
<body>
<div id='container'>
</div>
</body>
</html>
<script type = 'text/jsx'>
class FilteredList extends React.Component{
constructor(props){
super(props);
this.state={list:this.props.list};
}
filter(input){
var newList = this.state.list.filter(function(item){
return (item.search(input.target.value)!=-1);
});
this.setState({list:newList});
}
render(){
return(
<div>
<input type='text' placeholder='Filter' onChange={this.filter.bind(this)} />
<List items={this.state.list} />
</div>
);
}
}
class List extends React.Component{
constructor(props){
super(props);
this.state={items:this.props.items};
}
static getDerivedStateFromProps(nextProps, prevState) {
console.log('hello1');
if (nextProps.items !== prevState.items) {
return {
items: nextProps.items,
};
}
// Return null if the state hasn't changed
return null;
}
componentDidUpdate(nextProps,prevState){
console.log('hello2');
if(nextProps.items !== prevState.items)
this.setState({items:nextProps.items});
}
render(){
return(
<ul>
{this.state.items.map(function(item){
return(<li key={item}>{item}</li>);
})}
</ul>
);
}
}
ReactDOM.render(
<div><FilteredList list={['anteater','bear','cat','dog','elephant','fox']} /></div>,
document.getElementById('container')
);
</script>