Child 组件正在更改 parent 组件状态

Child component changing parent component state

这里有一个应用程序根组件通过克隆将 handleHeaderTitle 函数传递给它的所有 children。 在 children 个组件中,函数在 componentWillMount() 中被调用 结果根组件根据路由更新 header 文本。

根:

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

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

Child:

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

这是添加 redux 的正确用例吗,因为这里的状态不是真正的本地状态,而是从其 parent 上的 child 组件设置的?

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

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

在 React 中解决您的特定问题的更常见方法是将您的布局包含在 child 组件而不是根组件中。这避免了试图让 child 控制 parent 中的内容的问题。它有助于保留 "unidirectional data flow",这就是 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>
    )
  }
}