反应在数组中设置新对象仅在地图中设置纬度项

时间:2019-08-29 16:55:19

标签: reactjs state

我试图动态设置状态,以便为我的reactTable创建列标题。当我遍历对象以获取标头字段的属性时,我想将新列添加到状态中的columns数组中,但是它仅将对象数组中的最后一项添加到columns数组中。在使用新列设置状态之前,我正在克隆状态,但是显然我丢失了一些东西。提前致谢。

class ExpandedReactTable extends React.Component {
    constructor(props) {
        super(props);

        /*state values are dynamic*/
        this.state = {
            columns: []
        }
    }

    componentDidMount() {
        this.props.dispatch(actions.getProjectedDataList());
    }

/*Just pulling the first object from the array and getting the field names - these field names will be set as the column headers in the table*/

componentDidUpdate(prevProps) {
        if (prevProps.dataList !== this.props.dataList && this.props.dataList.length > 0) {
            Object.keys(this.props.dataList[0]).map(key => {
                this.setState({ [key]: true }); //this is getting set correctly

//now - set each column object in state.
//at this end, the columns state only has the last object that was mapped over
                this.setState({
                    columns: [...this.state.columns,
                    {
                        Header: [key, <br />, <input type="checkbox" name={key} checked={this.state[key]} onChange={(e) => this.updateColumnShow(key)} />],
                        accessor: key,
                        show: true
                    }]
                })
            })
        }
    }

我应该以columns数组中的7个对象结束,但是最后以最后一个映射到的对象结束:

columns [{Header: :{object}, accessor: value, show: boolean}],

1 个答案:

答案 0 :(得分:0)

由于setState异步,因此您必须像这样使用setState的prevState:

componentDidUpdate(prevProps) {
    if (prevProps.dataList !== this.props.dataList && this.props.dataList.length > 0) {
        Object.keys(this.props.dataList[0]).map(key => {
            this.setState({ [key]: true }); //this is getting set correctly

            this.setState(prevState => {
                columns: [...prevState columns,
                {
                    Header: [key, <br />, <input type="checkbox" name={key} checked={this.state[key]} onChange={(e) => this.updateColumnShow(key)} />],
                    accessor: key,
                    show: true
                }]
            })
        })
    }
}

调用循环时状态不会更新。 PrevState将是先前的设置状态,这应该可以工作。

希望这会有所帮助。编码愉快。