【问题标题】:SetState isn't populating an arraySetState 没有填充数组
【发布时间】:2021-02-03 09:47:18
【问题描述】:

我是 React 新手,所以这可能是一个愚蠢的问题。我正在尝试从 API 获取数据并将其填充到另一个数组中。 API 部分工作正常,因为我能够控制台记录数据。不起作用的是,使用 this.setState 将数据从 initialCustomerTypeList 移动到 CustomerTypeList 数组。 console.log 在 CustomerTypeList 上显示一个空数组,我不知道为什么。

代码:

  this.state1 = {
            CustomerTypeList: [],
        };

        this.onClick = this.onClick.bind(this);
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
     
          }

    componentDidMount() {
        let initialCustomerTypeList = [];
        fetch('api/CustomerType')
            .then(response => {
                return response.json();
            }).then(data => {
                initialCustomerTypeList = data.map((customertypeLine) => {
                    return customertypeLine
                });
                console.log("Initial Data" , initialCustomerTypeList);
                this.setState({
                   CustomerTypeList : initialCustomerTypeList
                 
                })
                console.log("CustomerTypeList" , this.state1.CustomerTypeList);
            })

同样,initialCustomerTypeList 有数据,只是没有将其移动到 CustomerTypeList。此外,它在 this.state1 中,因为我已经声明了一个 this.state 来保存来自输入字段的数据。

编辑:我也尝试将 CustomerTypeList 添加到原始 this.state(未图示),但我得到了相同的结果。

【问题讨论】:

  • 我第一眼看到 2 个问题,1)您使用的是 state1 而不是 state,2)setState 是异步的,所以当您尝试控制台更新状态的结果时尚未完成更新操作,要查看它更新,您可以尝试在组件的渲染函数中添加此 cide {console.log("CustomerTypeList" , this.state.CustomerTypeList)} 这将确保 `console 在状态更新后运行。
  • 我确实将其更改为 state 并将其与下面的答案结合起来,它现在似乎可以工作了。我假设您的反应组件中可以有多个 this.state,对吗?
  • 很高兴它对你有用,你不能在反应中每个组件有超过一个 state 对象(但是每个组件都有自己的 state 对象),但你可以在state 对象,例如 state = {firstName: "Shmili", lastName:"Breuer", hobbies: ["gardening","fishing"]},当您通过 setState 像这样 this.setState({firstName: "Shmily"}) 更新状态时,react 只更新您正在更新的属性。

标签: javascript reactjs react-native


【解决方案1】:

改变

this.state1 = {
            CustomerTypeList: [],
        };

this.setState({
               CustomerTypeList : initialCustomerTypeList
             
            })
            console.log("CustomerTypeList" , this.state1.CustomerTypeList);

this.state = {
            CustomerTypeList: [],
        };

this.setState({ CustomerTypeList : initialCustomerTypeList},
           () => console.log("CustomerTypeList" , this.state1.CustomerTypeList);
     );
            

【讨论】:

  • 我从 state1 中删除了“1”。现在它只是读取 this.state.CustomerTypeList。但你的回答奏效了。谢谢。
【解决方案2】:

React 会批量更新状态。因此,您可能无法读取调用 setState() 的 state 属性帖子,因为它本质上是异步的。

https://code.likeagirl.io/reactjs-dealing-with-asynchronous-state-updates-ff6ac4d24b05

【讨论】:

  • 感谢您的链接。这很好地解释了状态更新。
【解决方案3】:

我认为问题可能是您使用的是this.state1 而不是this.state,请尝试登录this.state.CustomerTypeList

【讨论】:

    【解决方案4】:

    需要一些改进

     this.state = {
       CustomerTypeList: []
     }
    

    设置数据

         componentDidMount() {
            let CustomerTypeList= [];
            fetch('api/CustomerType')
                .then(response => {
                    return response.json();
                }).then(data => {
                    CustomerTypeList = data.map((customertypeLine) => {
                        return customertypeLine
                    });
                    this.setState({
                       CustomerTypeList
                    }, ()=> console.log(this.state.CustomerTypeList))
                })
          }
    

    不要在将数据设置为状态后立即检查/控制台,因为它会异步更新。您可以检查/控制台作为setState() 方法的回调。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-14
      • 2017-03-30
      • 1970-01-01
      • 2022-01-26
      • 2019-11-24
      • 2019-03-22
      • 1970-01-01
      • 2021-11-18
      相关资源
      最近更新 更多