简体   繁体   English

Redux动作道具意外行为

[英]Redux action props unexpected behavior

I'm trying to post some data through a redux action and there is a problem I can't find. 我正在尝试通过redux操作发布一些数据,但找不到我有的问题。

As you can see on the picture , I use console.log to first display what I am passing to the action. 如您在图片上看到的,我使用console.log首先显示要传递给操作的内容。 There isn't any problem and every field is correctly filled. 没问题,每个字段都正确填写。

Then I use console.log to display the props received by the action. 然后,我使用console.log显示该动作收到的道具。 As you can see, the fields are messed up, they all are in one variable. 如您所见,字段被弄乱了,它们都在一个变量中。

Here is the simplified code : 这是简化的代码:

Component 零件


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);

Action : 动作:

// 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);
};

I can't find where the problem occurs, since the data that I pass to the action is correct, but the received one is not. 我找不到问题出在哪里,因为我传递给操作的数据是正确的,但收到的数据却不正确。 I'm sure this is a stupid error, but I can't find it. 我确定这是一个愚蠢的错误,但我找不到它。 Any help? 有什么帮助吗?

You are expecting spreaded arguments: 您期望spreaded争论:

export const updateProfile = (firstname, lastname, image, history) =>{}

And passing as a single object: 并作为单个对象传递:

updateProfile({ firstname, lastname, image, history })

Just change the function signature (actually destructure the args) to expect an object or spread the arguments in the function call: 只需更改函数签名(实际上将arg解构)以期望有一个对象或在函数调用中散布参数即可:

export const updateProfile = ({firstname, lastname, image, history}) =>{}
updateProfile(...formData)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM