如何以正确的方式读取组件内部的 redux 状态?



我无法理解如何将组件与我的 redux 状态连接(以正确的方式(

到目前为止,我尝试使用 mapStateToProps,但完全不知道之后数据存储在哪里,我什至设法在构造函数中获取了一个实例,但它也感觉不对,在其他组件中(以奇怪的方式构建(我看到程序员只是凭空拉出状态,但在我的组件(这是一个扩展"组件"的类(中,我只能通过手动更改每个组件来获得所需的结果在mapStateToProps中更改。

我尝试获取状态的组件(检查 mapStateToProps 中的注释,这就是我想要的(

import React, { Component } from "react";
import { connect } from "react-redux";
import {initCreate} from "../../actions" 
const mapDispatchToProps = dispatch => {
return {
initCreate: () => dispatch(initCreate())
};
};
const mapStateToProps = state => {
//this.state.toggleCreate = state.reduction.toggleCreate;  <= seems to work, but feels wrong? is this how it's done in react? 
return state.reduction;
};
class CrudBar extends Component {
constructor(reduction) {
super();
this.state = { toggleCreate: false};
this.create = this.create.bind(this);
}
create() {
this.props.initCreate();
setTimeout(() => {
console.log('state in component', this.state); // prints the state unchanged
}, 1000);
}
render() {
return (
<div>
<button onClick={this.create}>Create</button>
</div>
)
}
}
const toolBar = connect(mapStateToProps, mapDispatchToProps)(CrudBar);
export default toolBar;

操作.js

export const addCategory = category => ({ type: "ADD_CATEGORY", payload: category });
export const initCreate = state => ({ type: "CRUDBAR_CREATE", payload: state });

我的减速器:

const initialState = {
toggleCreate: false,
};
const reductionReducer = (state = initialState, action) =>{
switch (action.type) {
case "CRUDBAR_CREATE":
console.log('here') // printed
setTimeout(() => {
console.log('redux state', state); // prints the state changed
}, 1000);
return {
toggleCreate: !state.toggleCreate,
};
default:
return state;
}
};
export default reductionReducer;

程序员凭空提取状态的代码:

import React from "react";
import { connect } from "react-redux";
const mapStateToProps = state => {
return state.categories;
};
const CategoriesList = ({ categories }) => ( // I want something like this, to get the information and render accordingly
<ul>
{
categories.map(el => (
<li key={el.id}>
{/* Name, Address, Coordinates, and Category. */}
Name - {el.name}
</li>
)) }
</ul>
);
const List = connect(mapStateToProps)(CategoriesList);
export default List;

我希望组件从 redux 中读取状态, 我想以正确的方式做到这一点,而不是其他程序员不得不跳舞和畏缩的廉价技巧。

要使用 redux 状态,您需要从存储中获取它并将其注入组件 props。

这样做的方法是首先创建一个函数,该函数返回特定组件中所需的 redux 状态片段,如下所示

const mapStateToProps = ({pieceOfReduxState, anotherPieceOfReduxStete}) =>
({pieceOfReduxState, anotherPieceOfReduxStete})

这返回 2 个 redux 状态

然后将其作为第一个参数注入到连接函数

connect(mapStateToProps)(ComponentName)

这将使 redux 存储在您的组件属性中可用

然后只需通过访问this.props.pieceOfReduxState在您的组件中使用它

希望这有帮助。

相关内容

  • 没有找到相关文章