如何使用 Redux-thunk 派发功能
How dispatch function with Redux-thunk
我尝试使用 Redux-thunk 的分派函数,但出现错误 Actions must be plain objects。使用自定义中间件进行异步操作
index.js
import { Provider } from 'react-redux';
import thunk from 'redux-thunk';
import { App } from './components/App'
import reducer from './services/store/reducer';
const store = createStore(reducer,
compose(window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__(),
applyMiddleware(thunk)
)
)
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById('root')
);
行动
export const getTicketsData = () => async (dispatch) => {
dispatch(setLoadingStatus());
const { searchId } = await getSearchID();
dispatch(setSearchID(searchId));
try {
const { tickets, stop } = await getTickets(searchId);
dispatch(addTicketsData(tickets));
dispatch(setLoadedStatus());
dispatch(allTicketsLoaded(stop));
} catch (error) {
console.log(error)
dispatch(serverError());
}
}
组件
useEffect(() => {
dispatch(getTicketsData());
}, []);
不明白,请帮忙
在index.js需要改变applyMiddleware <-> window.__REDUX_DEVTOOLS...
const store = createStore(combineReducers(rootReducer()),
compose(
applyMiddleware(thunk),
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
)
)
我尝试使用 Redux-thunk 的分派函数,但出现错误 Actions must be plain objects。使用自定义中间件进行异步操作
index.js
import { Provider } from 'react-redux';
import thunk from 'redux-thunk';
import { App } from './components/App'
import reducer from './services/store/reducer';
const store = createStore(reducer,
compose(window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__(),
applyMiddleware(thunk)
)
)
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById('root')
);
行动
export const getTicketsData = () => async (dispatch) => {
dispatch(setLoadingStatus());
const { searchId } = await getSearchID();
dispatch(setSearchID(searchId));
try {
const { tickets, stop } = await getTickets(searchId);
dispatch(addTicketsData(tickets));
dispatch(setLoadedStatus());
dispatch(allTicketsLoaded(stop));
} catch (error) {
console.log(error)
dispatch(serverError());
}
}
组件
useEffect(() => {
dispatch(getTicketsData());
}, []);
不明白,请帮忙
在index.js需要改变applyMiddleware <-> window.__REDUX_DEVTOOLS...
const store = createStore(combineReducers(rootReducer()),
compose(
applyMiddleware(thunk),
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
)
)