简体   繁体   English

如何在 React Redux 中访问商店 state?

[英]How do I access store state in React Redux?

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.我只是制作一个简单的应用程序来学习与 redux 的异步。我已经完成了所有工作,现在我只想在网页上显示实际的 state。 Now, how do I actually access the store's state in the render method?现在,我如何在渲染方法中实际访问商店的 state?

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.title from the store.因此,在 state 的渲染方法中,我想列出商店中的所有item.title

Thanks谢谢

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

Import connect from react-redux and use it to connect the component with the state connect(mapStates,mapDispatch)(component)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>
    );
  }
}

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

You need to use Store.getState() to get current state of your Store.您需要使用Store.getState()来获取商店的当前状态。

For more information about getState() watch this short video.有关getState()更多信息,请观看短片。

You want to do more than just getState .您想做的不仅仅是getState You want to react to changes in the store.您想对商店中的变化做出反应。

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.但更好的是使用 react-redux。 In this case you use the Provider like you mentioned, but then use connect to connect your component to the store.在这种情况下,您可以像提到的那样使用 Provider,然后使用connect将您的组件连接到商店。

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

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

Place that in the file where you do createStore .将其放在您执行createStore的文件中。

To copy the state object 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.右键单击 Chrome 控制台中的对象,然后从上下文菜单中选择存储为全局变量。 It will return something like temp1 as the variable name.它将返回类似 temp1 的内容作为变量名。

  2. Chrome also has a copy() method, so copy(temp1) in the console should copy that object to your clipboard. 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/

All of the answers are from pre-hook era.所有的答案都来自前钩时代。 You should use useSelector-hook to get the state from redux.您应该使用 useSelector-hook 从 redux 获取状态。

In your redux-reducer file or somewhere where you can import it easily:在您的 redux-reducer 文件或您可以轻松导入的地方:

import { useSelector } from 'react-redux'

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

In your application code:在您的应用程序代码中:

const { employees } = useEmployees()

More information on redux-hooks: https://react-redux.js.org/api/hooks to accomplish this goal.有关 redux-hooks 的更多信息: https ://react-redux.js.org/api/hooks 以实现此目标。

HACK SOLUTION : Example from my REAL project . HACK 解决方案:来自我的真实项目的示例。 Save Redux store objects to external JSON file将 Redux 存储对象保存到外部 JSON 文件

STEP-1 import useStore first from react-redux and then getState() function is used to access store state. STEP-1 import useStore 首先从 react-redux 然后 getState() function 用于访问存储 state。

STEP-2 area is the name of my slice in Redux store and areaName is state in that slice. STEP-2区域是我在 Redux 存储中的切片名称,并且 areaName 是该切片中的 state。

STEP-3 FiletoSave variable is used to export JSON file with data from store. STEP-3 FiletoSave 变量用于从存储中导出 JSON 文件和数据。

import { useStore } from "react-redux";

const exportJsonFileFromStore = () => {

const store = useStore();
const FileSaver = require('file-saver');    
    
function exportData() {
   
    const filename = 'filter_settings';

    let prepareObject = {       // It is used to make a JSON object 
      areaName:store.getState().area.areaName  ,   
    }
    const fileToSave = new Blob([JSON.stringify(prepareObject)], {
        type: 'application/json'
    });
    // this will save file
    FileSaver.saveAs(fileToSave, filename);
}

return (
  
        <button onClick={(event: any) => exportData()}>Click me to download!</button>
   
)

} }

import { ReactReduxContext } from 'react-redux';从'react-redux'导入{ReactReduxContext};

var store = useContext(ReactReduxContext).store.getState(); var store = useContext(ReactReduxContext).store.getState();

console.log(store);控制台日志(存储);

https://react-redux.js.org/using-react-redux/accessing-store#using-reactreduxcontext-directly https://react-redux.js.org/using-react-redux/accessing-store#using-reactreduxcontext-directly

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我如何在 react redux 中访问另一个 reducer 的状态。 reducer 和 store 之间的状态流 - How do i access state of one reducer in other in react redux. State flow between reducers and store 我如何从另一个 React 组件访问 redux 状态? - How do i access redux state from another react component? 如何在同一反应组件中使用本地状态以及redux存储状态? - How do I use local state along with redux store state in the same react component? 如何访问 Safari 中的 redux 商店? - How do I access the redux store in Safari? 更改 redux 商店 state 后,如何重定向到我的反应应用程序中的另一个页面? - How do I redirect to another page in my react app after changing the redux store state? 在React with Redux中从我的商店/状态中删除项目后,如何更新视图 - How do I get my view to update after an item was removed from my store/State in React with Redux 我尝试在商店中恢复 state (react, redux) - I try to recover a state in store (react, redux) 使用 Redux 工具包,我如何从非反应文件访问商店? - Using Redux Toolkit, how do I access the store from a non-react file? 如何在 Redux 应用程序的 localstorage 中存储我的状态? - How do I store my state in localstorage in my Redux application? 我如何通过反应导航访问 redux 商店? - How can i access to redux store with react navigation?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM