React-如何在数组类型状态下添加新元素? [英] React - how to add new element in array type state?

查看:978
本文介绍了React-如何在数组类型状态下添加新元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已引用链接以找到解决方案,但它们都不对我有用

I have refereed this , this and this link to find solution but none of them work for me.

我已经清除了数组类型的状态和其他具有null的状态.

I have decleared state with array type and other state with null.

this.state = {  from: '', to: '',journeyDate: '',searchDetails: [] }

当用户用源城市,目的地城市和旅行日期填写搜索表单时,我将这些状态设置如下.

As user fill up search form with source city , destination city and journey date I set these state like below .

    let from = this.state.from;
    let to = this.state.to;
    let journeyDate = moment(this.state.journeyDate).format('YYYY-MM-DD'); 

最后一步,将所有这些变量推入searchDetails数组状态.为此,我尝试了以下选项,但没有一个起作用.

final step to push these all variables into searchDetails array state. for that I have tried below options but none of them worked.

选项1

this.setState({ searchDetails: [...this.state.searchDetails, from] });

选项2

this.setState(prevState => ({
            searchDetails: [...prevState.searchDetails, from]
        }))

选项3

let newState = this.state.searchDetails.slice();
        newState.push(from);

        this.setState({
            searchDetails: newState
        });
      console.log('final state is : ' + this.state.searchDetails);

每次控制台日志保持为空.

every time console log remains empty.

有什么建议吗?

推荐答案

尝试:

this.setState({
    searchDetails: newState // use any of your 3 methods to set state
},() => {
     console.log('final state is : ' + this.state.searchDetails);
});

setState()并不总是立即更新组件.有可能 批量更新或将更新推迟到以后.

setState() does not always immediately update the component. It may batch or defer the update until later.

这使得阅读this.state 在调用setState()之后立即陷入陷阱.

This makes reading this.state right after calling setState() a potential pitfall.

使用 componentDidUpdate或setState回调(setState(updater, 回调)),保证在更新后都会触发 已应用.如果您需要根据之前的状态来设置状态 状态,请阅读下面的updater参数.

Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied. If you need to set the state based on the previous state, read about the updater argument below.

有关更多详细信息,请阅读: https://reactjs.org/docs/react-component.html#setstate

For More Detail, Please read : https://reactjs.org/docs/react-component.html#setstate

这篇关于React-如何在数组类型状态下添加新元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆