【问题标题】:Child component changing parent component state子组件改变父组件状态
【发布时间】:2017-07-10 12:52:06
【问题描述】:

这里有一个应用根组件通过克隆将一个handleHeaderTitle 函数传递给它的所有子组件。 在子组件内部,该函数在 componentWillMount() 中调用 因此根组件会根据路由更新标题文本。

根:

    {
         this.props.children &&
                    React.cloneElement(this.props.children, {
                      handleHeaderTitle: this.handleHeaderTitle
                    })
    }

    handleHeaderTitle(title) {
      this.setState({ headerTitle: title });
    }

孩子:

 componentWillMount() {
    this.props.handleHeaderTitle("Profile");
  }
  Profile.propTypes = { handleHeaderTitle: React.PropTypes.func };

这是添加 redux 的正确用例,因为这里的状态并不是真正的本地状态,因为它是从其父组件上的子组件设置的?

我想我需要创建像 SET_PROFILE_HEADER 和内部 reducer 这样的操作,将它们结合起来。但仍在弄清楚如何通知容器根组件子组件已更改标题标题

【问题讨论】:

    标签: reactjs redux react-redux


    【解决方案1】:

    要直接回答您的问题,您不需要 Redux 来解决您的问题。当您必须维护大量状态时,或者当您的状态需要反映应用程序中没有密切共同祖先的部分时,Redux 可以帮助您。换句话说,当使用老式的 React 状态变得太麻烦时。

    解决 React 中特定问题的更常见方法是将布局包含在子组件中而不是根组件中。这避免了试图让孩子控制父母中的内容的问题。它有助于保留 React 的“单向数据流”。

    class Page extends React.Component {
      render() {
        return (
          <div>
            <div className='profile-header'>
              { this.props.headerTitle }
            </div>
            <div className='profile-content'>
              { this.props.children }
            </div>
          </div>      
        )
      }
    }
    
    class MyFirstPage extends React.Component {
      render() {
        return (
          <Page headerTitle='Header Title 1'>
              <div>My content here</div>
          </Page>
        )
      }
    }
    

    【讨论】:

    猜你喜欢
    • 2021-06-08
    • 2016-12-23
    • 1970-01-01
    • 2020-12-30
    • 2019-09-21
    • 2021-06-30
    • 1970-01-01
    • 2020-01-13
    • 2019-04-04
    相关资源
    最近更新 更多