【问题标题】:componentWillReceiveProps not firing even props value updatedcomponentWillReceiveProps 即使更新了道具值也不会触发
【发布时间】:2017-07-11 14:07:40
【问题描述】:

有一个简单的场景,我更新了父组件中的一个值,该值传递给子组件并预期 cWRP 方法触发但没有。下面是代码;

父组件:

class App extends Component {
  changeProps(){//interpreter jumps here fine..
    debugger
    this.appState.index=15 //update props value
  }
  render() {
    return (
      <div className="App">
        <EasyABC parentUpdateProps={this.changeProps} appState={this.props.appState} />
      </div>
    )
  }
}

子组件:

@observer
export default class EasyABC extends Component{
    constructor(props){
        super(props)
    }
    componentWillReceiveProps(nextProps){//why its not jump here after update props in parent?
        debugger
    }
    playSound(){// when this method called, cWRP above should be invoked rigth?
        this.props.parentUpdateProps()
    }

render(){
        return(
            <div>   
                <a onClick={()=> this.playSound()}>Play Sound Again</a>

已编辑:我正在使用 mobx 作为状态处理程序,但不要打扰它

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    您需要使用 setState 更新组件的状态并将其传递给子组件

    class App extends Component {
      constructor() {
        this.state = {
          index: 0,
        };
        this.changeProps = this.changeProps.bind(this);
      }
    
      changeProps(){
        this.setState({
          index: 15,
        });
        // this will update state (not props)
      }
      render() {
        return (
          <div className="App">
            <EasyABC
              parentUpdateProps={this.changeProps}
              appState={...this.state}
            />
          </div>
        );
      }
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

    【讨论】:

      【解决方案2】:

      您错误地更新了state。你必须使用setState 例如

      changeProps() {
          this.setState({
              index: 15
          });
      }
      

      【讨论】:

        【解决方案3】:

        你必须在 render 函数中取消引用 observable 值,否则它不会触发 will receive props,因为组件实际上并没有使用它来渲染。

        你可以这样做:

        render() {
          if (this.props.appState.index) {
            return <div>Play Sound Again</div>;
          }
        
          return <div>Play Sound</div>;
        }
        

        你如何使用它并不重要,重要的是你在渲染方法的调用堆栈中访问它。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-03-29
          • 1970-01-01
          • 2019-03-12
          • 2021-08-31
          • 2011-12-23
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多