How to dynamically get state array name React

2019-08-03 08:03发布

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:

error Image

Any help would be greatly appreciated, Thanks

1条回答
相关推荐>>
2楼-- · 2019-08-03 08:49

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
            })
        }))
    }
}
查看更多
登录 后发表回答