我只是做一个简单的应用程序来学习与redux异步。我已使所有工作正常进行,现在我只想在网页上显示实际状态。现在,我实际上如何在render方法中访问商店的状态?
这是我的代码(所有内容都在一页中,因为我只是在学习):
const initialState = {
fetching: false,
fetched: false,
items: [],
error: null
}
const reducer = (state=initialState, action) => {
switch (action.type) {
case "REQUEST_PENDING": {
return {...state, fetching: true};
}
case "REQUEST_FULFILLED": {
return {
...state,
fetching: false,
fetched: true,
items: action.payload
}
}
case "REQUEST_REJECTED": {
return {...state, fetching: false, error: action.payload}
}
default:
return state;
}
};
const middleware = applyMiddleware(promise(), thunk, logger());
const store = createStore(reducer, middleware);
store.dispatch({
type: "REQUEST",
payload: fetch('http://localhost:8000/list').then((res)=>res.json())
});
store.dispatch({
type: "REQUEST",
payload: fetch('http://localhost:8000/list').then((res)=>res.json())
});
render(
<Provider store={store}>
<div>
{ this.props.items.map((item) => <p> {item.title} </p> )}
</div>
</Provider>,
document.getElementById('app')
);
因此,在状态的render方法中,我想item.title
从存储中列出所有内容。
谢谢
react-redux
库创建一个商店连接的组件。我强烈建议您使用作者的免费课程来增进您对redux的理解:egghead.io/courses/getting-started-with-redux