gpt4 book ai didi

reactjs - 我应该使用 Redux store.subscribe() 还是用react-redux 包装我的应用程序?

转载 作者:行者123 更新时间:2023-12-02 10:43:29 33 4
gpt4 key购买 nike

我见过两种方法:在 this example ,摘自 Dan Abramov 的类(class),他正在使用这种方法:

const render = () => {
ReactDOM.render(
<Counter
value={store.getState()}
onIncrement={() =>
store.dispatch({
type: 'INCREMENT'
})
}
onDecrement={() =>
store.dispatch({
type: 'DECREMENT'
})
}
/>,
document.getElementById('root')
);
};

store.subscribe(render);

Redux 中的 store.subscribe() 函数允许添加在调度操作时调用的监听器。

在此other example ,这是 Redux 文档中的一个示例:

render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)

不使用 store.subscribe,而是将整个应用程序包装在 <Provider> 中。组件。

这两种方法有什么区别?看来他们在做同样的事情,就是确保App拥有最新版本的状态。

如果我用<Provider>包装了我的应用程序,我可以/应该使用Store.subscribe吗? ?

最佳答案

可以使用第一种方法,但是您应该在将来将存储传递给所有其他组件。手动执行此操作需要大量工作,但除此之外它还会使事情变得困难,例如测试等。

Provider 不是 Redux 的一部分,但附带了 react-redux 以使事情变得更容易。你用它包裹你的组件,它会一直向下传递存储。 react-redux还提供了connect功能。您可以在组件中任何想要到达操作调度程序和状态的地方使用它。

因此,您可以很容易地看到,使用 Provider 组件几乎是事实上的标准。因此,您可能想使用它,并且不必费心手动执行 store.subscribe 并将您的商店传递给其他组件。因此,如果您使用 Provider,您将不会使用 store.subscribe

render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)

然后,在另一个您想要使用 redux 优点的组件中:

const Component = ...

const mapStateToProps = (state) => ({
value: state.someValueFromState
});

const mapDispatchToProps = { action, otherAction };

export default connect(
mapStateToProps,
mapDispatchToProps
// or you can use action creators directly instead of mapDispatchToProps
// { action, otherAction }
)(Component);

然后,您可以使用操作创建者和状态值作为组件中的 Prop 。

关于reactjs - 我应该使用 Redux store.subscribe() 还是用react-redux <Provider> 包装我的应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53580710/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com