简体   繁体   English

React.js 数据未保存到 state 变量

[英]React.js data not saving to state variable

I'm trying to render my workersData and ordersData however after fetching the APIs, ordersData can be rendered by using map, but when I try to render workersData it doesn't do anything.我正在尝试渲染我的workerData和ordersData,但是在获取API之后,可以使用map渲染ordersData,但是当我尝试渲染workerData时它什么也没做。 I checked with console.log and seems it does get populated with the right data but when I try to map it, it won't render it.我检查了 console.log,似乎它确实填充了正确的数据,但是当我尝试 map 它时,它不会呈现它。 I'm fairly new to React so any help is appreciated.我对 React 还很陌生,因此感谢您提供任何帮助。

class FetchData extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            ordersData: [],
            workersDatas: [],
        };
    }

    componentDidMount() {
        fetch("https://www.hatchways.io/api/assessment/work_orders")
            .then(response => response.json())
            .then(data => {
                this.setState({
                    ordersData: data.orders
            }, () => { 
                    console.log(this.state.ordersData)
                    this.state.ordersData.map(order => {
                        console.log(this.state.ordersData)
                        fetch(`https://www.hatchways.io/api/assessment/workers/${order.workerId}`)
                            .then(result => result.json())
                            .then(data2 => {
                                this.state.workersDatas.push(data2);
                            })
                        console.log(this.state.workersDatas)
                    })
                });
            })
            .catch(err => {
                console.log(err)
            });
    }

    render() {
        return (
            <div>
                <ul>
                  {this.state.workersDatas.map(order => (
                    <li>
                      hello
                    </li>
                  ))}
                </ul>
            </div>
        );
    }
}

ReactDOM.render(<FetchData/>, document.getElementById('root'));

it's because, this.setState() may be update the state asynchronously, so don't get the state as soon as you update the state.这是因为, this.setState()可能会异步更新 state,所以不要在更新 state 后立即获取 state。 this document is maybe helpful for understanding the state.文档可能有助于理解 state。

this.state.workersDatas.push(data2) is a no-no. this.state.workersDatas.push(data2)是禁止的。

Do Not Modify State Directly . 不要直接修改 State It will not re-render your components.它不会重新渲染您的组件。 This could be why you see the correct data in your console, but not in your component.这可能就是您在控制台中看到正确数据但在组件中看不到的原因。

To make your fetch data flow easier to read, break it down into chunks instead of trying to nest multiple callbacks.为了使您的获取数据流更易于阅读,请将其分解为块,而不是尝试嵌套多个回调。 Fetch the ordersData and set the state.获取 ordersData 并设置 state。 Then use that state to fetch the workersData, and set it using the spread operator.然后使用该 state 获取workerData,并使用扩展运算符对其进行设置。

  componentDidMount() {
    fetch("https://www.hatchways.io/api/assessment/work_orders")
      .then(response => response.json())
      .then(data => {
        this.setState({
          ordersData: data.orders
        });
      })
      .then(() => {
        this.state.ordersData.forEach(order => {
          console.log(this.state.ordersData);
          fetch(
            `https://www.hatchways.io/api/assessment/workers/${order.workerId}`
          )
            .then(result=> result.json())
            .then(data2 => {
              this.setState(prevState => ({
                workersDatas: [data2, ...prevState.workersDatas]
              }));
            });
          console.log(this.state.workersDatas);
        });
      })
      .catch(err => {
        console.log(err);
      });
  }

编辑 cocky-goodall-c6ok7

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM