0

我有以下“列表”组件,我正在尝试从道具更新 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>
4

1 回答 1

1

升级到 v5.2.1 或更高版本,这个未解决的问题应该是修复 yarn upgrade -L react-helmet

我认为您需要 16.3.1 或更高版本,可能需要 16.3.3

于 2019-12-11T02:52:43.303 回答