[英]How should I use “redux-thunk” for Async Initial state ? (react/redux)
[英]Async initial state React-Redux Redux-Thunk
使用React
、 Redux
、 Redux-thunk
我想通过服务器请求(API 调用)获得初始状态,但我似乎无法让它工作。
到目前为止我得到了什么:
var Redux = require('redux');
var carReducer = require('./reducers/cars');
var thunk = require('redux-thunk').default;
var initialState = require('./reducers/initialState');
var rootReducer = Redux.combineReducers({
cars: carReducer
});
module.exports = Redux.applyMiddleware(thunk)(Redux.createStore)(rootReducer, initialState.loadInitial());
这是我最初的商店创建。 我的InitialState
看起来像这样:
var $ = require('jquery');
module.exports = {
loadInitial: loadInitial
};
function loadInitial() {
return {
cars: [
{}
]
}
}
当我尝试将此loadInitial
转换为$.get('api/...')
,Redux 告诉我我需要一个初始状态才能使其工作。
在我的减速器中,我有一个加载方法:
function updateReducer(state, action) {
switch (action.type) {
case 'load':
return action.data;
case 'update':
return updateCars(action.data, state);
default:
return action.data || initialState.loadInitial().cars;
}
};
但同样,如果我使用 - 作为默认值 - 异步调用,它似乎不起作用。
我真正想要的是使用来自数据库的任何内容来初始化我的商店。 这是我的 HandsonTable 所需要的,因为我将属性传递给了表,并且正如我现在拥有的那样,它只会为我呈现一行,因为我的初始状态只有一个对象。
奇怪的是,当我点击表格时,它实际上获取了我所有的行,因为数据已加载,但我猜为时已晚。
无论如何,我的问题是,如何通过对后端的 api 调用来初始化我的商店?
你可以给它一个空白的初始状态(空对象或者可能只是一个加载消息),当你的 API 调用回来时,你可以更新状态,你的组件将因此用新数据重绘。 您可以做的另一件事是在调用返回您的数据之前不初始化您的组件。
编辑包括示例
在组件的生命周期方法之一中(甚至可能在 getInitialState 中):
getInitialState: function() {
var oThis = this;
$.get({
url: 'api...',
success: function (...) {
oThis.setState({...data returned by server});
}
});
return {};
}
或者,沿着这些路线的东西:
$.get({
url: 'api...',
success: function (...) {
var oStore;
// oStore = response from server
ReactDOM.render(
<ReactRedux.Provider store={oStore}>
<MyComponent/>
</ReactRedux.Provider>
, document.getElementById()
);
}
});
对于 redux 初始状态,您无法传递异步值,因此您需要传递一些静态空对象(就像您的示例中那样)并调用一个操作以从服务器获取初始状态并替换您的状态。 为了简化所有这些过程,您可以使用redux async 初始状态中间件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.