React Redux如何调度操作



我目前正在学习redux,并且很难弄清楚如何调度操作。我有一个带有输入字段的组件,我希望保存用户键入的文本,以便在另一个页面上显示它。

这是我的行动:

export const addMovement = () => {
const response = {
movement: {
name: '',
weight: '',
} 
}
return {
type: constants.ADD_MOVEMENT,
payload: response
}

};

这是我的减速器:

const intialState = {
movement: {
name: '',
weight: '',
} 
};
const movementReducer = (state = intialState, action) => {
switch (action.type) {
case GET_MOVEMENT:
return [ ...state, action.payload ]
default:
return state;
}
};
export default movementReducer;

这是我的组件:

const AddPage = () => {
const [name, setName] = useState('');
const [weight, setWeight] = useState(0);
const onSubmit = () => {
addMovement();
}
return (
<div>
<Header title="Add Page" />
<div>
<div>
<TextField  
key="name" 
label="Enter Movement Name" 
InputProps= {{className: "textBoxColor"}}
variant="outlined"
onChange={event => {
const { value } = event.target;
setName(value);
}} 
/>    
<TextField 
key="weight" 
label="Enter Movement Weight" 
type="number" 
variant="outlined"
onChange={event => {
const { value } = event.target;
setWeight(value);
}}
InputProps= {{endAdornment: <InputAdornment position="end">lb</InputAdornment> }} />
<Button 
variant="outlined"
onClick={ onSubmit }
>
<AddCircleIcon />
</Button>
</div>
</div>
</div>
);
};
const mapStateToProps = (state) => {
return {
newName: state.name,
newWeight: state.weight,
}
};
const mapDispatchToProps = (dispatch) => {
return (
dispatch(addMovement)
)
};
const withConnect = connect(
mapStateToProps,
mapDispatchToProps,
);
export default compose(withConnect)(AddPage)

如有任何帮助,将不胜感激

可以用一个例子来最好地解释

如果您想将当前用户对象设置为冗余状态

export const SetcurrentUser = user => ({
type: 'SET_CURRENT_USER',
payload: user
});

为了使用用户参数调用SetcurretUser操作。

function mapDispatchToProps(dispatch) {
return({
SetcurrentUser: (user) => dispatch(SetcurrentUser(user))
})
}

现在就您而言:

案例:1如果您的Redux州需要有效负载

//take response as parameter in your action you may destructure it if necessary
export const addMovement = (response) => {
return {
type: constants.ADD_MOVEMENT,
payload: response
}

};
function mapDispatchToProps(dispatch) {
return({
addMovement: (response) => dispatch(addMovement(response))
})
}

情况:2如果只需要操作,则不需要有效载荷

export const addMovement = () => {
return {
type: constants.ADD_MOVEMENT,
}

};
function mapDispatchToProps(dispatch) {
return({
addMovement: () => dispatch(addMovement())
})
}

在学习过程中,您可以使用带钩子的功能组件。在redux钩子中,很容易从存储中读取,也很容易使用useSelector()useDispatch()钩子调度操作。

const items = useSelector(state => state.reducerName.itemName)

您可以尝试使用React社区推荐的功能组件编写代码

相关内容

  • 没有找到相关文章

最新更新