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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38332912/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:20:30  来源:igfitidea点击:

How do I access store state in React Redux?

javascriptasynchronousreactjsreduxreact-redux

提问by Parkicism

I am just making a simple app to learn async with redux. I have gotten everything working, now I just want to display the actual state onto the web-page. Now, how do I actually access the store's state in the render method?

我只是在制作一个简单的应用程序来学习与 redux 的异步。我已经让一切正常,现在我只想在网页上显示实际状态。现在,我如何在渲染方法中实际访问商店的状态?

Here is my code (everything is in one page because I'm just learning):

这是我的代码(所有内容都在一页中,因为我只是在学习):

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

So, in the render method of the state I want to list out all the item.titlefrom the store.

因此,在 state 的 render 方法中,我想列出item.title商店中的所有内容。

Thanks

谢谢

采纳答案by 1ven

You should create separate component, which will be listening to state changes and updating on every state change:

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

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

回答by Zakher Masri

Import connectfrom react-reduxand use it to connect the component with the state connect(mapStates,mapDispatch)(component)

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

Finally you need to map the states to the props to access them with this.props

最后,您需要将状态映射到道具以访问它们 this.props

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

Only the states that you map will be accessible via props

只有您映射的州才能通过 props

Check out this answer: https://stackoverflow.com/a/36214059/4040563

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

For further reading : https://medium.com/@atomarranger/redux-mapstatetoprops-and-mapdispatchtoprops-shorthand-67d6cd78f132

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

回答by semanser

You need to use Store.getState()to get current state of your Store.

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

For more information about getState()watch thisshort video.

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

回答by Brandon

You want to do more than just getState. You want to react to changes in the store.

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

If you aren't using react-redux, you can do this:

如果你没有使用 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

But better is to use react-redux. In this case you use the Provider like you mentioned, but then use connectto connect your component to the store.

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

回答by Let Me Tink About It

If you want to do some high-powered debugging, you can subscribe to every change of the state and pause the app to see what's going on in detail as follows.

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

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

Place that in the file where you do createStore.

将其放在您执行的文件中createStore

To copy the stateobject from the console to the clipboard, follow these steps:

要将state对象从控制台复制到剪贴板,请执行以下步骤:

  1. Right-click an object in Chrome's console and select Store as Global Variable from the context menu. It will return something like temp1 as the variable name.

  2. Chrome also has a copy()method, so copy(temp1)in the console should copy that object to your clipboard.

  1. 右键单击 Chrome 控制台中的对象,然后从上下文菜单中选择存储为全局变量。它将返回类似 temp1 的内容作为变量名。

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

https://stackoverflow.com/a/25140576

https://stackoverflow.com/a/25140576

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

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

You can view the object in a json viewer like this one: http://jsonviewer.stack.hu/

您可以在这样的 json 查看器中查看对象:http: //jsonviewer.stack.hu/

You can compare two json objects here: http://www.jsondiff.com/

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