How to dynamically get state array name React

老子叫甜甜 提交于 2019-12-14 02:32:44

问题


How can I dynamically set the name of the array in state, to get it from state.

onCheckBoxItemClickList(e, value, path) {
    console.log(e.target.checked)
    if (e.target.checked) {
        //append to array
        this.setState({
            [path]: this.state.[path].concat([value])
        })
    } else {
        //remove from array
        this.setState({
            [path]: this.state.[path].filter(function (val) {
                return val !== value
            })
        })
    }
}

I know how to dynamically set and get a key in state, but when I try and do

[path]: this.state.[path].concat([value])

I get the below error:

Any help would be greatly appreciated, Thanks


回答1:


You have an extra dot in your code (after state):

[path]: this.state.[path].concat([value])

Should be:

[path]: this.state[path].concat([value])

Then whenever you want to set the state based on the previous state, you should use the setState which takes a callback in, with the prevState as argument.

So your code should look something like:

onCheckBoxItemClickList(e, value, path) {
    console.log(e.target.checked)
    if (e.target.checked) {
        //append to array
        this.setState(prevState => ({
            [path]: prevState[path].concat([value])
        }))
    } else {
        //remove from array
        this.setState(prevState => ({
            [path]: prevState[path].filter(function (val) {
                return val !== value
            })
        }))
    }
}


来源:https://stackoverflow.com/questions/54129355/how-to-dynamically-get-state-array-name-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!