gpt4 book ai didi

reactjs - React-Redux,状态未正确更新

转载 作者:行者123 更新时间:2023-12-04 04:05:22 25 4
gpt4 key购买 nike

我有一个小的发票应用程序,它应该在列表中显示发票并且还能够添加新的/编辑旧的发票。

状态由 redux 管理,绑定(bind)由 React-redux 完成。

在我尝试用我的表单值调用 useDispatch 钩子(Hook)之前,一切都很顺利。它 dispatch 正确的值,但在到达 reducer 的过程中,行数组中的所有数据都消失了。全部其他数据被正确发送。

发送到 reducer 的表单值:

dispatch(newInvoice({
"id": 4,
"name": " xvsvsd",
"street": "vsdvs",
"zip": "sdfss",
"city": "sefsd",
"due_date": "2020-07-01",
"rows": [
{
"quantity": 5,
"currency": "eur",
"unit_price": 3,
"unit_of_measurement": "kpl",
"vat": 4,
"name": "test",
},
{
"quantity": 4,
"currency": "eur",
"unit_price": 3,
"unit_of_measurement": "kpl",
"vat": 4,
"name": "test1",

}]

}))

我的行动

export const newInvoice = (props) => {
console.log(props)

return {
type: 'ADD_NEW',
data: {

id: props.id,
name: props.name,
street: props.street,
zip: props.zip,
city: props.city,
due_date: props.due_date,
rows: [
{
quantity: props.rows.quantity,
currency: props.rows.currency,
unit_price: props.rows.unit_price,
unit_of_measurement: props.rows.unit_of_measurement,
vat: props.rows.vat,
name: props.rows.name,
},
]
}
}
}

我的 reducer

const invoiceReducer = (state = initialState, action) => {
switch(action.type) {
case 'ADD_NEW':
console.log(state)
console.log(action.data)
return [...state, action.data ]

default:
return state
}
}

编辑你问的是 initialState,是这样的:

[
{
"id": 1,
"name": "Test company",
"street": "Testikatu 1",
"zip": "00100",
"city": "Helsinki",
"due_date": "2020-08-01",
"rows": [
{
"quantity": 3,
"currency": "EUR",
"unit_price": 1.24,
"unit_of_measurement": "kpl",
"vat": 24,
"name": "Sample invoice row 1"
},
{
"quantity": -1,
"currency": "EUR",
"unit_price": 2.48,
"unit_of_measurement": "kpl",
"vat": 24,
"name": "Sample invoice row 2"
}
]
},
{
"id": 2,
"name": "Another test company",
"street": "Testikatu 3",
"zip": "00100",
"city": "Helsinki",
"due_date": "2020-08-05",
"rows": [
{
"quantity": 1,
"currency": "EUR",
"unit_price": 150,
"unit_of_measurement": null,
"vat": 0,
"name": "Sample row"
}
]
}
]

当我 console.log action.data 时,它在行数组的所有字段上显示未定义。

提前致谢。

最佳答案

尝试像这样修改你的 Action

export const newInvoice = (props) => {
console.log(props)

return {
type: 'ADD_NEW',
data: {

id: props.id,
name: props.name,
street: props.street,
zip: props.zip,
city: props.city,
due_date: props.due_date,
rows: props.rows.map(row => ({...row})
}
}
}

因为你的行是一个数组所以如果你尝试直接访问没有索引的行它会给出未定义的

关于reactjs - React-Redux,状态未正确更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62592785/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com