简体   繁体   English

在 React 组件外部更新 redux state

[英]Update redux state outside React component

I have a react project configured with redux for state management.我有一个配置了 redux 的反应项目,用于 state 管理。 For api calls I use a file called axiosInstance.对于 api 调用,我使用一个名为 axiosInstance 的文件。 In this file I need to have access to redux store (and I have access importing store and using getState - store.getState()).在这个文件中,我需要访问 redux 存储(并且我可以访问导入存储并使用 getState - store.getState())。 Now the problem is that I want also to update the redux state from this file (axiosInstance).现在的问题是我还想从这个文件(axiosInstance)更新 redux state。 How I can update redux store from this file (which is not a react component) in a efficient method?如何以有效的方法从此文件(不是反应组件)更新 redux 存储?

Okay, I assume that you are using Axios for the network calls.好的,我假设您使用 Axios 进行网络调用。

tl;dr tl;博士

Use store.dispatch(action) and action to make changes to store state使用store.dispatch(action)和 action 进行更改以存储 state

Yes, the store can be accessed with store.getState() , you can also change state with store.dispatch(action) .是的,可以使用store.getState()访问商店,您也可以使用store.dispatch(action)更改 state。 as per the docs根据文档

Dispatches an action.调度一个动作。 This is the only way to trigger a state change.这是触发 state 更改的唯一方法。

The store's reducing function will be called with the current getState() result and the given action synchronously.商店的减少 function 将与当前的 getState() 结果和给定的动作同步调用。 Its return value will be considered the next state.其返回值将被视为下一个 state。 It will be returned from getState() from now on, and the change listeners will immediately be notified.从现在开始,它会从 getState() 中返回,并且会立即通知更改监听器。

This happens because of the functional paradigm that redux follows (google for more).这是因为 redux 遵循的功能范例(谷歌了解更多)。

Now, the action has to be defined with anactionCreator , or simply you could call .dispatch() with an inline object with one string property as {type: 'name-of-action'} .现在,必须使用actionCreator定义操作,或者您可以简单地调用 .dispatch .dispatch()并使用内联 object ,其中一个字符串属性为{type: 'name-of-action'} This prompts the store to change the state.这会提示商店更改 state。 You may require redux-thunk for async actions.您可能需要 redux-thunk 来执行异步操作。

Conclusion:结论:

Let's save some trouble here as you may have many calls to the store, you can create a context that handles the AxiosInstance (as there is already a different file for that).让我们在这里省点麻烦,因为您可能对存储有很多调用,您可以创建一个处理 AxiosInstance 的上下文(因为已经有一个不同的文件)。

Make a context in the AxiosInstance file and then you can start dispatching actions as per the network responses.在 AxiosInstance 文件中创建一个上下文,然后您可以根据网络响应开始调度操作。 this will save you a lot of trouble as the state is updated by redux without actually looking at it much.这将为您省去很多麻烦,因为 state 是由 redux 更新的,而实际上并没有看太多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM