reactjs - 一次更新多个组件的状态

标签 reactjs

我有一个 ListView 组件,它由许多子列表项组件组成。

每个子列表项都有一个 showSubMenu bool 状态,它在列表项旁边显示一些额外的按钮。

此状态应更新以响应用户事件,例如单击组件 DOM 节点。

子组件:

_handleClick() {
  ... mutate state
  this.props.onClick() // call the onClick handler provided by the parent to update the state in parent
}

但是,更新状态感觉有点不对劲,因为它会在不同的地方改变状态。

我认为可以实现它的另一种方法是直接调用 this.props.onClick ,并将子状态作为 Prop 移动到父级中,然后更改那里的状态,并将其作为 Prop 滴下来。

这些方法中哪一个(如果有)是惯用的或更可取的?

最佳答案

首先,我认为问题的标题并没有很好地描述你的疑问是什么。更多的是关于国家应该走向何方的问题。

theory React 的说法是,您应该将状态放在您可以找到的更高组件中,因为它是一组组件的单一事实来源。

For each piece of state in your application:

  • Identify every component that renders something based on that state.
  • Find a common owner component (a single component above all the components that need the state in the hierarchy).
  • Either the common owner or another component higher up in the hierarchy should own the state.
  • If you can't find a component where it makes sense to own the state, create a new component simply for holding the state and add it somewhere in the hierarchy above the common owner component.

然而,Facebook 的软件工程师 said :

We started with large top level components which pull all the data needed for their children, and pass it down through props. This leads to a lot of cruft and irrelevant code in the intermediate components. What we settled on, for the most part, is components declaring and fetching the data they need themselves...

当然,谈论的是从商店获取的数据,但我想说的是,在某些情况下,该理论并不是最佳选择。

在这种情况下,我会说 showSubMenu 状态仅对列表项显示几个按钮有意义,因此最好将该状态放入子组件中。我说这是一个很好的选择,因为这是一个简单问题的简单解决方案,您提出的另一个选项意味着具有类似 this 的内容:

var GroceryList = React.createClass({
  handleClick: function(i) {
  console.log('You clicked: ' + this.props.items[i]);
},

render: function() {
  return (
    <div>
      {this.props.items.map(function(item, i) {
        return (
          <div onClick={this.handleClick.bind(this, i)} key={i}>{item} </div>
        );
      }, this)}
    </div>
  );
}
});

例如,如果将来 ListView 必须获得该状态的确认才能显示某些内容,则该状态应该位于父组件中。

但是,我认为这是一条细线,您可以在您的具体情况下做任何有意义的事情,我的应用程序中有一个非常相似的情况,这是一个简单的情况,所以我将状态放在 child 中。明天也许我必须更改它并将状态放入他的父级中。

关于reactjs - 一次更新多个组件的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30232124/

相关文章:

javascript - 使用 js 映射选中的复选框

reactjs - Gatsby:使用localStorage存储数据

javascript - 警告 : Failed propType: Invalid prop 'component' supplied to 'route'

javascript - 如何在 react 中从url获取数据

javascript - react-cookie 无法设置过期或 maxAge

javascript - 重新格式化对象数组

javascript - React.js 嵌套树拖放

reactjs - 如何获取 react 元素的宽度

javascript - 具有 'as' 属性的通用 React TypeScript 组件(能够渲染任何有效的 dom 节点)

reactjs - 最简单的 Typescript + React + WebPack 示例生成错误