简体   繁体   English

高阶组件未触发ReactJS中的包装渲染

[英]Higher Order Component not firing wrapper render in ReactJS

I'm using a high order component that is not rendering the child on a render change. 我正在使用一个高级组件,该组件不会在渲染更改上渲染子级。 The code below has been chopped down for simplicity sake. 为了简单起见,下面的代码已被截断。

The HOC that looks like this: 如下所示的HOC:

const withMyComponent = (WrapperComponent) => {
    class HOC extends Component {
        state = {
            value: ''
        };

        changedHandler = (event) => {
            this.setState({ value: event.target.value });
        };

        render() {
            return (<WrapperComponent {...this.props}
                changed={this.changedHandler}
                value={this.state.value} />);
        }
    };

    return HOC;
};

export default withMyComponent;

Then I have a child component that uses this HOC: 然后,我有一个使用此HOC的子组件:

class myChildComponent extends Component {
    render() {
        return (
            <input type="text"
                onChange={(event) => this.props.changed(event)}
                value={this.props.value || ''} />
        );
    };
};

export default withMyComponent(myChildComponent);

The problem I am experiencing is that the input is not updating with the new value that is passed back from the HOC. 我遇到的问题是input没有使用从HOC传回的新值更新。 In fact, the child render is not even firing after the initial mount and doesn't seem to fire on any changed event. 实际上,子渲染在初始安装后甚至不会触发,并且似乎不会在任何已更改的事件上触发。

I have placed debugging and console.logs in the HOC render and the changed event and the render are firing with the proper data. 我将调试和console.logs放置在HOC渲染中,并且更改后的事件和渲染使用正确的数据触发。

So, if I type in the textbox, it fires the change event in the HOC and updates the state in the HOC and fires the render event in the HOC. 因此,如果我在文本框中键入内容,它将在HOC中触发change事件,并在HOC中更新状态,并在HOC中触发render事件。 But it is not firing the wrapped components render event, and thus the textbox never updates with any values. 但是它不会触发包装的组件的render事件,因此文本框永远不会更新任何值。

Anyone able to solve this issue or lead me in the right direction? 任何人都可以解决这个问题或将我引向正确的方向吗?

Thanks again. 再次感谢。

You need to pass an object to this.setState 您需要将一个对象传递给this.setState

const withMyComponent = WrapperComponent => {
  class HOC extends Component {
    state = {
      value: ""
    };

    changedHandler = event => {
      // Instead of 
      // this.setState( value: event.target.value );

      // Do This.
      this.setState({ value: event.target.value });
    };

    render() { ... }
  }

  return HOC;
};

Working Demo 工作演示

编辑zq6vk36z3m

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM