javascript – 如何在React Redux中访问存储状态?

前端之家收集整理的这篇文章主要介绍了javascript – 如何在React Redux中访问存储状态?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我只是简单的应用程序来学习与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'));
原文链接:https://www.f2er.com/js/154093.html

猜你在找的JavaScript相关文章