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

How do I access store state in 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, 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')
);

因此,在状态的呈现方法中,我想列出商店中的所有 item.title

谢谢

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

有关 getState() 的更多信息,请观看 this 短视频。

您应该创建单独的组件,它将监听状态变化并在每次状态变化时更新:

import store from '../reducers/store';

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'));

您想做的不只是 getState。您想对商店中的变化做出反应。

如果你没有使用 react-redux,你可以这样做:

function rerender() {
    const state = store.getState();
    render(
        <div>
            { state.items.map((item) => <p> {item.title} </p> )}
        </div>,
        document.getElementById('app')
    );
}

// subscribe to store
store.subscribe(rerender);

// do initial render
rerender();

// dispatch more actions and view will update

但更好的是使用 react-redux。在这种情况下,您可以像您提到的那样使用 Provider,然后使用 connect 将您的组件连接到商店。

react-redux导入connect并用它来连接组件与状态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://medium.com/@atomarranger/redux-mapstatetoprops-and-mapdispatchtoprops-shorthand-67d6cd78f132

如果你想做一些高性能的调试,你可以订阅状态的每一次变化,然后暂停应用程序来查看详细情况,如下所示。

store.js
store.subscribe( () => {
  console.log('state\n', store.getState());
  debugger;
});

将其放在文件中 createStore

要将 state 对象从控制台复制到剪贴板,请按照下列步骤操作:

  1. 右键单击 Chrome 控制台中的对象,然后从上下文菜单中 select 存储为全局变量。它会 return 像 temp1 这样的变量名。

  2. Chrome 也有一个 copy() 方法,因此控制台中的 copy(temp1) 应该将该对象复制到剪贴板。

https://scottwhittaker.net/chrome-devtools/2016/02/29/chrome-devtools-copy-object.html

您可以在 json 查看器中查看对象,如下所示:http://jsonviewer.stack.hu/

您可以在此处比较两个 json 对象:http://www.jsondiff.com/

所有答案都来自pre-hook时代。您应该使用 useSelector-hook 从 redux 获取状态。

在您的 redux-reducer 文件中或您可以轻松导入它的地方:

import { useSelector } from 'react-redux'

export function useEmployees() {
  return useSelector((state) => state.employees)
}

在您的应用代码中:

const { employees } = useEmployees()

有关 redux-hooks 的更多信息:https://react-redux.js.org/api/hooks 以实现此目标。