【发布时间】:2019-12-15 13:26:18
【问题描述】:
我无法理解如何将组件与我的 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;
actions.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 中读取状态, 而且我想以正确的方式做到这一点,而不是其他程序员不得不跳舞和畏缩的廉价技巧。
【问题讨论】:
标签: reactjs redux components