我是reactjs的新手,正在创建一个小项目,我使用功能组件而不是类组件,并使用状态存储。我已经添加了一些状态变量,并想在退出状态下添加对象数组,我尝试了一下,但是没有用。下面是我的商店文件的设置状态:
export const initialState = {
validationTally: 0,
token: '',
multiForm : []
}
// action types
const SET_VALIDATION_TALLY = 'SET_VALIDATION_TALLY';
const SET_TOKEN = 'SET_TOKEN';
const SET_MULTIFORM = 'SET_MULTIFORM';
export const reducer = (state, action) => {
switch (action.type) {
case SET_VALIDATION_TALLY:
return {
...state,
validationTally: state.validationTally + 1
};
case SET_TOKEN:
return {
...state,
token: action.payload
};
case SET_MULTIFORM:
return {
...state,
multiForm: action.payload
};
}
}
export const setValidationTally = () => ({
type: SET_VALIDATION_TALLY
});
export const setToken = payload => ({
type: SET_TOKEN,
payload
});
export const setMultiForm = payload => ({
type: SET_MULTIFORM,
payload
});
我想在状态变量“ multiForm”中动态添加对象,当有人输入值2时,我想在“ multiForm”中添加两个对象,如下所示:
export const initialState = {
validationTally: 0,
app: '',
token: '',
multiForm : [{
firstName : '',
lastName :''
},
{
firstName : '',
lastName :''
}]
}
答案 0 :(得分:0)
假设action.payload
的{{1}}操作包含要添加的字段数,您可以简单地映射到数组项并添加到现有字段中
SET_MULTIFORM