Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/blackberry/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs React中不同对象的通用设置状态函数_Reactjs - Fatal编程技术网

Reactjs React中不同对象的通用设置状态函数

Reactjs React中不同对象的通用设置状态函数,reactjs,Reactjs,我有一个相当基本的组件,它在状态中包含两个对象 export default class MainForm extends Component { constructor(props) { super(props); this.state = { time_frame: {}, event_view: {}, } } } 这些对象中的每一个都包含一个值名,如果我的用户单击某个复选框,则为

我有一个相当基本的组件,它在状态中包含两个对象

export default class MainForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            time_frame: {},
            event_view: {},
       }
   }
}
这些对象中的每一个都包含一个值名,如果我的用户单击某个复选框,则为true,因此它会建立一个值列表,如

"event_view": {"app":true, "web":true}
为了处理更改,我创建每个对象的一个副本,然后填充用户选择的值,我想知道是否有一种通用的方法可以在React中实现这一点?而不必检查
event.target.name

我的方法似乎不是很有效

handleRadioChange(event) {
    let name = event.target.name
    let timeFrameCopy = {...this.state.time_frame};
    let eventViewCopy = {...this.state.event_view};

    if (name === "time_frame") {
        timeFrameCopy[event.target.value] = true
        this.setState({
            [name]: timeFrameCopy,
        }, this.checkState)
        return
    }

    if (name === "event_view") {
        eventViewCopy[event.target.value] = true
        this.setState({
            [name]: eventViewCopy,
        }, this.checkState)
        return
    }
}

您可以尝试此操作,也可以保存以前的状态

this.setState(prevState => ({
  ...prevState,
  [name]: value
}))