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

我只是做一个简单的应用程序来学习与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商店中的所有内容

谢谢

Green前端2020/03/14 18:19:17

您需要使用Store.getState()获取商店的当前状态。

有关getState()观看短片的更多信息

小卤蛋猴子猪猪2020/03/14 18:19:17

connect从中导入react-redux并使用它来将组件与状态连接connect(mapStates,mapDispatch)(component)

import React from "react";
import { connect } from "react-redux";


const MyComponent = (props) => {
    return (
      <div>
        <h1>{props.title}</h1>
      </div>
    );
  }
}

最后,您需要将状态映射到道具以使用 this.props

const mapStateToProps = state => {
  return {
    title: state.title
  };
};
export default connect(mapStateToProps)(MyComponent);

您只能通过以下方式访问您映射的州 props

看看这个答案:https : //stackoverflow.com/a/36214059/4040563

进一步阅读:https : //medium.com/@atomarranger/redux-mapstatetoprops-and-mapdispatchtoprops-shorthand-67d6cd78f132