状态不会保持更新

时间:2020-08-27 18:49:35

标签: reactjs

setState中使用getClients()后,状态clientOptions正确显示。但是,当我尝试将其传递给子组件时,它是一个空数组。我尝试在componentDidMount之后再次记录它,看来状态clientOptions已重置为其原始状态([])。抱歉,如果这似乎是一个菜鸟问题,我现在就开始做出新反应了。

class Main extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      clientFilter: 'ALL',
      positionFilter: 'ALL',
      clientOptions: []
    };
  }

  componentDidMount = () => {
    this.getClients()
    this.getTitles()
    console.log('this one shows only []: ' + this.state.clientOptions)
  }
  
  getClients = () => {
    axios.get('http://localhost:5000/clients')
    .then((response) => {
      let clientObj = [{value: 'ALL', label: 'ALL'}];
      const clientOptions = []

      response.data.forEach(function (client, index) {
        clientObj.push({value: client.name, label: client.name})
      });
      clientOptions.push({'options' : clientObj});

      this.setState(prevState =>{
        return{
             ...prevState,
             clientOptions : clientOptions
        }
     })
     console.log('this one works: ' + this.state.clientOptions)
    });
  }

根据要求将状态传递给孩子:

  render() {
    return (
      <div className="main">
        <Header 
          clientOptions={this.state.clientOptions}
        />
      </div>
    );
  }

0 个答案:

没有答案