Redux 调度操作时,我的减速机中的状态不会更改
我无法检索减速机中的Redux 调度操作时,我的减速机中的状态不会更改,redux,react-redux,Redux,React Redux,我无法检索减速机中的状态 MyComponent看起来像这样 const MyComponent = ({name, features, onClick}) => { return ( <div> Hello! {name} <Button onClick={() => { onClick(features); }}> Weight</Button> </di
状态
MyComponent看起来像这样
const MyComponent = ({name, features, onClick}) => {
return (
<div>
Hello! {name}
<Button onClick={() => { onClick(features); }}> Weight</Button>
</div>
);
const mapDispatchToProps = (dispatch: any) => {
return {
onClick: (features) => {
dispatch(weightSort(features));
}
};
};
const mapStateToProps = (state: any, ownProps: any) => {
console.log(state); //Displays the state
return {
name: "John Doe",
features: ownProps.features,
};
};
export const FeatureBlock = connect(mapStateToProps, mapDispatchToProps)(MyComponent);
我错过了什么?任何帮助都将不胜感激 在您的reducer中,当您
console.log(state)
时,返回空数组是正确的,因为您没有做任何修改
// Reducer
export const weightFilter = (state = [1,2,3], action) => {
switch (action.type) {
case "SET_WEIGHT_FILTER":
console.log(state); // This will show [1,2,3] because [1,2,3] is the initial state.
console.log("++inside weight filter+++++", action); //Displays action
return state;
default:
return state;
}
};
我猜你希望你的减速机有这样的功能:
// Action Creator
export const weightSort = (name, features) => {
console.log("inside the weight sort action creator!!!");
return {
type: "SET_WEIGHT_FILTER",
name,
features,
};
};
// Reducer
export const weightFilter = (
state = {
name: '',
features: [],
},
action
) => {
switch (action.type) {
case "SET_WEIGHT_FILTER":
return {...state, name: action.name, features: action.features}
default:
return state;
}
};
然后在mapStateToProps
中,您可以这样映射属性:
const mapStateToProps = (state: any, ownProps: any) => {
console.log(state); //Displays the state
return {
name: state.weightFilter.name,
features: state.weightFilter.features,
};
};
您的按钮将有一个名称道具传递到函数中,如下所示:
<Button onClick={() => { onClick(name, features); }}> Weight</Button>
以下是关于sortBy的lodash文档:
希望有帮助 谢谢你的回复。如果必须根据按钮对功能进行排序,请单击如何进行?(我希望将排序包括在组件中,就像您正确指出的那样)如果我想将其放入mapDispatchToProps
函数mapDispatchToProps=({
OnFeatures单击:orderFeatures
})
您将如何做到这一点?您将创建一个以对象属性名称命名的动作分派,以便将其传递给减速器。在reducer中,可以使用操作传递的属性对reducer中的数据进行排序并返回新对象。另一个选项是在呈现数据的容器中创建一个state属性,如sortProperty
,并将onClick处理程序绑定到设置sortProperty上的state的按钮。然后在映射到项目的表中,使用排序函数对项目进行排序。
<Button onClick={() => { onClick(name, features); }}> Weight</Button>
import { sortBy } from 'lodash' //be sure to npm install lodash if you use this utility
...
...
function mapStateToProps(state) {
return {
name: state.weightFilter.name,
features: sortBy(features, ['nameOfPropertyToSortBy'])
};
}