[英]How to use redux-thunk correctly, with React?
I am trying to get my app not to complain that action does not have an undefined type property.我试图让我的应用程序不要抱怨 action 没有未定义的类型属性。
I have set up my client side render as follows:我已经设置了我的客户端渲染如下:
import React from 'react';
import ReactDOM from 'react-dom';
import routes from './shared/routes';
import rootReducer from './shared/reducers';
import thunk from 'redux-thunk';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
let initialState = window.__INITIAL_STATE_;
const store = createStore(rootReducer, initialState, applyMiddleware(thunk));
ReactDOM.render(
<Provider store={store}>
{routes}
</Provider>, document.getElementById('app'));
Which I believed to be the correct way?我认为哪个是正确的方法?
Yes.是的。 In the redux-thunk github page there's a great example of how to use it.
在redux-thunk github 页面中有一个很好的示例说明如何使用它。
For your actions, if it's an async action, I'm using this approach to dispatch an async action with promises:对于您的操作,如果它是一个异步操作,我将使用这种方法来发送带有承诺的异步操作:
Action:行动:
export function add({name, time}) {
return dispatch => {
dispatch({type: ADD});
return postJSON('/api/services', {
name,
time,
})
.then(service => {
dispatch({
type: ADD_SUCCESS,
service: service,
});
})
.catch(error => {
dispatch({
type: ADD_FAILURE,
error,
});
});
};
}
Inside my component:在我的组件中:
addService () {
const { dispatch } = this.props;
return (fields) => {
dispatch(add(fields));
dispatch(toggleAddForm());
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.