如何访问 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

谢谢

273858 次浏览

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

有关 getState()的更多信息,请观看 这个短片。

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

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

如果你不使用反应还原,你可以这样做:

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

但最好是用反应还原法。在这种情况下,像您提到的那样使用 Provider,然后使用 连接将组件连接到存储。

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

Only the states that you map will be accessible via props

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

进一步阅读: 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 控制台中的一个对象,然后从上下文菜单中选择“存储为全局变量”。它将返回一些类似于 tem1的变量名。

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

Https://stackoverflow.com/a/25140576

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://www.jsondiff.com/

All of the answers are from pre-hook era. You should use useSelector-hook to get the state from redux.

在你的 redux-reduce 文件或者其他你可以轻松导入的地方:

import { useSelector } from 'react-redux'


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

在您的应用程序代码中:

const { employees } = useEmployees()

更多关于 redux-hook 的信息: https://react-redux.js.org/api/hooks来实现这个目标。

黑客解决方案 : 我的 REAL 项目示例! 将 Redux 存储对象保存到外部 JSON 文件。

Import useStore 首先从 response-reducx 开始,然后使用 getState ()函数访问存储状态。

STEP-2 area 是 Redux store 中我的切片的名称,areaName 是该切片中的状态。

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>
   

)

}