簡體   English   中英

Redux動作道具意外行為

[英]Redux action props unexpected behavior

我正在嘗試通過redux操作發布一些數據,但找不到我有的問題。

如您在圖片上看到的,我使用console.log首先顯示要傳遞給操作的內容。 沒問題,每個字段都正確填寫。

然后,我使用console.log顯示該動作收到的道具。 如您所見,字段被弄亂了,它們都在一個變量中。

這是簡化的代碼:

零件


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

我找不到問題出在哪里,因為我傳遞給操作的數據是正確的,但收到的數據卻不正確。 我確定這是一個愚蠢的錯誤,但我找不到它。 有什么幫助嗎?

您期望spreaded爭論:

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

並作為單個對象傳遞:

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

只需更改函數簽名(實際上將arg解構)以期望有一個對象或在函數調用中散布參數即可:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM