Redux的好处

red*_* 87 6 reactjs redux

我已经开始学习没有Redux或Flux的React,并且已经听到了很多有关Redux的信息,以及如何使用它来管理未来的状态。我的理解是,应用程序的整个状态都存在于商店中,我认为它位于React树的顶部。然后,各个子组件“订阅”到与其相关的各种状态。

这让我有些困惑,因为我认为React的核心结构已经以这种方式设置了?即,如果我的组件具有某种状态,则将其传递给其子组件,以便在更进一步的React树中使用时,我需要在this.state.example或this.props.example中添加到组件。对我来说,这种方式也是“订阅”组件的一种方式。

抱歉,如果不是这样的问题的正确答案,但是如果有人可以告诉我我在这里缺少什么,或者Redux的额外好处那将非常有帮助!

Zac*_*ltz 7

您在订阅部分上走的路是正确的,但是让Redux和其他许多类似状态管理模式的Flux出色的是,您不必将属性沿子链向下传递,因此您可以像这样更新子组件(如果您想要,但不需要,则可以):

function Parent() {
  return <ChildOne color="red" />
}

function ChildOne(props) {
  return <ChildTwo color={props.color} />
}

function ChildTwo(props) {
  return <h1>The Color was: {props.color}</h1>
}
Run Code Online (Sandbox Code Playgroud)

它允许您"dispatch"(一个redux / flux术语)action进入状态存储,以更新组件可能订阅的任何对象上的属性。

用于该“连接”的有用库是react-redux。它具有许多功能,但是我看到的主要connect是一个高阶组件(HOC),它用更多逻辑“包装”您的组件,包括您要订阅的redux存储部分。

所以上面可能是:

export class Parent extends React.Component {
   componentDidMount() {
     this.props.dispatch(changeColor('red'));
   }
   render() {
     return <ChildOne />
   }
}
export default connect((state) => ({ //This property is the redux store
  parent: state.parent,
}))(Parent) //higher order component that wraps the component with redux functionality

function ChildOne(){
  return (
     <ChildTwo />
  );
}

export function ChildTwo(props) { //will have childTwo bound in props object
  return (
    <h1>The Color is: {props.childTwo.color}
  );
}
export default connect((state) => ({ //This property is the redux store
  childTwo: state.childTwo,
}))
Run Code Online (Sandbox Code Playgroud)

最大的区别是您不必将颜色从Parent2层向下传递到,ChildTwo因为它是“订阅”到childTworedux存储内的对象的,因此您将该状态位连接到组件,因此对存储的任何更改都将触发组件从状态更改中重新呈现。

属性的传递和使用Redux可以通过中等程度的Presentationand Container组件来实现,在这种情况下,属性的传递才有意义,因为您只深入了一个子层,而容器组件正在处理ajax请求或调度到redux商店的一部分,等等。

  • 您可能还想阅读我与他人合写的最新文章,该文章有助于解释Redux在React应用程序中的好处:https://www.fullstackreact.com/articles/redux-with-mark-erikson/。 (2认同)