为什么使用 react-redux 而不仅仅是 redux?

Why use react-redux and not just redux?

顶级 App 组件在构造方法中订阅了 redux 存储:

constructor () {
  super()
  this.state = store.getState()
  store.subscribe(() => {
    this.setState(store.getState())
  })
}

它将部分状态作为道具传递给子组件。如果某个子组件需要更新状态,它只会派发一个动作:

<button onClick={() => { 
  store.dispatch({type: 'INCREMENT'}) }
}>increment</button>

与此设置相比,使用 react-redux 有什么优势?换句话说,我为什么需要 react-redux

如果您的组件树不是很深,那么您是对的。优势不是很明显。然而,大多数不是简单示例的 React 应用程序很快就会有很长的树,尤其是在将许多组件组合在一起时。

想象一下,你在一棵树上有一个血统

App -> HomePage -> BlogContainer -> PostList -> Post -> CustomCard -> Card -> LikeButton

LikeButton 组件需要访问当前选定的 post,并希望分派一个操作来更新 post 的点赞数。

在您的设置中,AppLikeButton 之间的每个组件都需要传递该信息,即使它们从不使用它也是如此。使用 react-reduxconnect 函数,您可以直接将 LikeButton 连接到 redux 存储,并可以访问 dispatch。 YMMV,但总的来说,这是一个很好的利用模式。

很多原因。

首先,根据 Redux FAQ answer on connecting multiple components:

Emphasizing “one container component at the top” in Redux examples was a mistake. Don't take this as a maxim. Try to keep your presentation components separate. Create container components by connecting them when it's convenient. Whenever you feel like you're duplicating code in parent components to provide data for same kinds of children, time to extract a container. Generally as soon as you feel a parent knows too much about “personal” data or actions of its children, time to extract a container.

换句话说,一个有意义的应用程序将在组件树的不同位置有 许多 个连接的组件。

更多连接的组件意味着更容易推断给定组件在做什么。它声明它需要来自状态的数据,以及它想要分派的动作,而且你不必为了将它们传递到该组件而从根部一路向下传递道具。

此外,拥有更多的连接组件已被证明可以提高整体性能。事实证明,更多 mapState 调用的成本被更少的组件进行无用的重新渲染所抵消。

在此之后:React-Redux 已经进行了 大量 优化工作(即将到来的 React-Redux v5 是一个完整的内部重写,具有主要性能改进)。

换句话说,如果您将 React 与 Redux 结合使用,您应该 使用 React-Redux 及其 connect 函数来构建你的 UI.

它的要点是关注点分离 - react-redux 允许仅访问和更改组件需要访问和更改的状态部分。

@lux 的评论最能回答我的问题,所以我将其粘贴在这里(强调我的):

Any subscription you create in Redux will get invoked on every state change, regardless of whether you need to do work on that state slice or not. react-redux allows us to specifiy which parts of the store certain components should subscribe to, and therefore we only "subscribe" to the changes we want

您可以通过 Redux 完成,并且仍然避免更新所有组件。是的,您可以调整当前组件是否应该更新。这是示例代码

 class VisibleTodos extends Component{
    componentDidMount(){
        this.unsubscribe = store.subscribe(() => {
           this.forceUpdate();
      });
    }

    componentWillUnmount() {
        this.unsubscribe();
    }


    render(){


        const state = store.getState();

        return(
            <TodoList
              todos = {getVisibleTodos(
                  state.todos,
                state.visibilityFilter
              )}
              onTodoClick = {id => {
                  store.dispatch({
                      type: 'TOGGLE_TODO',
                    id
                })
              }}
            >
            </TodoList>
        )
    }
}

与 react-redux 库相同的事情将完成

const mapStateToProps = (state) => {


return {
    todos: getVisibleTodos(
      state.todos,
      state.visibilityFilter
    )
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    onTodoClick: (id) => {
      dispatch({
        type: 'TOGGLE_TODO',
        id
      });
    }
  };
};

const { connect } = ReactRedux;
const VisibleTodoList = connect(
  mapStateToProps,
  mapDispatchToProps
)(TodoList);

所以假设还有其他几个组件与此类似,在前一种情况下,对 this.forceUpdate()this.unsubscribe() 的调用将是多余的。因此,它使我们免于手动工作。