【问题标题】:React setState nested object callback反应 setState 嵌套对象回调
【发布时间】:2020-07-30 02:53:12
【问题描述】:

我有一个父组件:

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 方法中,但我不确定如何解决。

【问题讨论】:

  • 这能回答你的问题吗? What is event pooling in react?
  • Event 对象在 React 中被复用,因此 Event 对象的 value 属性可能会发生变化。尽快从 Event 对象中获取所需的 w/e,然后将数据上游传递给 w/e 正在使用它。不要传递事件本身。从中获取你需要的东西,然后传递出去。

标签: javascript reactjs


【解决方案1】:

只需使用

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

【讨论】:

    猜你喜欢
    • 2020-08-04
    • 1970-01-01
    • 1970-01-01
    • 2017-10-22
    • 1970-01-01
    • 2020-01-04
    • 2021-11-09
    • 1970-01-01
    • 2019-06-02
    相关资源
    最近更新 更多