我只是简单的应用程序来学习与redux的异步.我有一切工作,现在我只想在网页上显示实际的状态.现在,我如何在渲染方法中实际访问商店的状态?
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,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.
谢谢
解决方法
您应该创建单独的组件,它将监听每个状态更改的状态更改和更新:
class Items extends Component { constructor(props) { super(props); this.state = { items: [],}; store.subscribe(() => { // When state will be updated(in our case,when items will be fetched),we will update local component state and force component to rerender with new data. this.setState({ items: store.getState().items; }); }); } render() { return ( <div> {this.state.items.map((item) => <p> {item.title} </p> )} </div> ); } }; render(<Items />,document.getElementById('app'));