反应setState嵌套对象回调

时间:2020-04-16 18:32:08

标签: javascript reactjs

我有一个父级组件:

class ParentComponent extends React.Component {

    constructor() {
            super();
            this.state = {
                filterInputs: {
                    priceMin: "",
                    priceMax: ""
                   // and many other similar nested fields
                }
            } 
            this.handleChange = this.handleChange.bind(this)
        }



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

    //render method omitted     
 }

我还有一个更深层的嵌套子组件:

    class GrandchildComponent extends React.Component {

        handleChange = e => {
            this.props.handleChange && this.props.handleChange(e)
        };

        render() {
            return (
                <div>
                            <InputText id="priceMin"
                                       value={this.props.filterInputs.priceMin}
                                       name="priceMin"
                                       onChange={this.handleChange}
                            />
                            <InputText id="priceMax"
                                       value={this.props.filterInputs.priceMax}
                                       name="priceMax"
                                       onChange={this.handleChange}
                            />

                            //And many other similar input fields
                </div>
            )
        }
    }

(我试图将代码尽量减少)

我遇到一种情况,用户正在填写一些输入字段,并且我试图使用回调方法handleChange将输入发送到我的父组件。 我收到错误消息:TypeError: Cannot read property 'name' of null,控制台显示:Warning: This synthetic event is reused for performance reasons. If you're seeing this, you're accessing the property ``target`` on a released/nullified synthetic event. This is set to null. If you must keep the original synthetic event around, use event.persist().

问题似乎出在我的handleChange方法中,但我不确定如何解决。

1 个答案:

答案 0 :(得分:1)

只需使用

this.setState({
  filterInputs: {
    ...this.state.filterInputs,
    [e.target.id]: e.target.value,
  }
});