Tik*_*kes 12 reactjs redux react-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());
Run Code Online (Sandbox Code Playgroud)
这是我最初的商店创作.我InitialState看起来像这样:
var $ = require('jquery');
module.exports = {
loadInitial: loadInitial
};
function loadInitial() {
return {
cars: [
{}
]
}
}
Run Code Online (Sandbox Code Playgroud)
当我尝试将其loadInitial转换为a时$.get('api/...'),Redux告诉我,我需要一个初始状态才能使其工作.
在我的reducer中我有一个加载方法:
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;
}
};
Run Code Online (Sandbox Code Playgroud)
但同样,如果我使用 - 作为默认设置 - 异步调用,它似乎不起作用.
我真正想要的是使用来自数据库的任何东西来初始化我的商店.这是我的HandsonTable所需要的,因为我将属性传递给表并且现在我已经将它传递给我,因为我的初始状态只有一个对象.
关于这一点的奇怪之处在于,当我点击表格时,它实际上得到了我所有的行,因为数据已加载,但我猜测为时已晚.
无论如何,我的问题是,如何通过api调用我的后端来初始化我的商店?
你可以给它一个空白的初始状态(空对象或者可能只是一个加载消息),当你的 API 调用回来时,你可以更新状态,你的组件将因此用新数据重绘。您可以做的另一件事是在调用返回您的数据之前不初始化您的组件。
编辑包括示例
在组件的生命周期方法之一中(甚至可能在 getInitialState 中):
getInitialState: function() {
var oThis = this;
$.get({
url: 'api...',
success: function (...) {
oThis.setState({...data returned by server});
}
});
return {};
}
Run Code Online (Sandbox Code Playgroud)
或者,沿着这些路线的东西:
$.get({
url: 'api...',
success: function (...) {
var oStore;
// oStore = response from server
ReactDOM.render(
<ReactRedux.Provider store={oStore}>
<MyComponent/>
</ReactRedux.Provider>
, document.getElementById()
);
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7442 次 |
| 最近记录: |