我正在尝试通过 redux 操作发布一些数据,但有一个问题我找不到。
正如您在 picture 上看到的那样,我使用 console.log
首先显示我传递给操作的内容。没有任何问题,每个字段都已正确填写。
然后我使用 console.log
来显示操作收到的 Prop 。如您所见,字段乱七八糟,它们都在一个变量中。
这是简化的代码:
组件
const Profile = ({ updateProfile, history }) => {
const [formData, setFormData] = useState({
firstname: '',
lastname: '',
image: '',
});
const { firstname, lastname, image } = formData;
//fields correctly filled
const onSubmit = async e => {
e.preventDefault();
console.log('firstname :', firstname);
console.log('lastname : ', lastname);
console.log('img : ', image);
updateProfile({ firstname, lastname, image, history });
};
[jsx form etc]
export default connect(
mapStateToProps,
{ updateProfile }
)(Profile);
行动:
// fields are regrouped in firstname variable
export const updateProfile = (firstname, lastname, image, history) => async dispatch => {
try {
console.log('action firstname :', firstname);
console.log('action lastname :', lastname);
console.log('action img :', image);
const body = JSON.stringify({ firstname, lastname, image });
console.log('action body :', body);
const res = await axios.put('/api/profile/me', body);
};
我找不到问题出在哪里,因为我传递给操作的数据是正确的,但接收到的数据却不正确。 我确定这是一个愚蠢的错误,但我找不到它。有帮助吗?
最佳答案
你期待展开
参数:
export const updateProfile = (firstname, lastname, image, history) =>{}
并作为单个对象传递:
updateProfile({ firstname, lastname, image, history })
只需更改函数签名(实际上是解构参数)以期待一个对象或在函数调用中传播参数:
export const updateProfile = ({firstname, lastname, image, history}) =>{}
updateProfile(...formData)
关于javascript - Redux action 支持意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57311330/