Redux 无法将对象推入数组

问题描述 投票:0回答:1

我正在尝试学习 redux,我面临着将多个对象推入

initialState
的问题,这是一个数组。我尝试了
push()
方法,但这不起作用。我的
action.payload
获得了提交者的价值,这是一个对象。

减速机功能:

import { NEWBOOK, DELETEBOOK } from "./actionTypes"

const initialState = [{}]

console.log(typeof(initialState))

const bookingReducer = (state = initialState, action) => {
  switch (action.type) {
    case NEWBOOK:
      return {
        ...state,
        stae: action.payload,
      }

    case DELETEBOOK:
      return { ...state }

    default:
      return { state }
  }
}

export default bookingReducer

调度数据:

const booked = useSelector((state) => state);
const dispatch = useDispatch();

const newBookDisp = (value) => {
  dispatch(newBook(value));
}

console.log(booked);
const [inputData, setInputData] = useState([]);
const handleOnChange = e => {
  const field = e.target.name;
    const value = e.target.value;
    const newInputData = { ...inputData };
    newInputData[field] = value;
    setInputData(newInputData);
}
  
const submitBook = (e) => {
  e.preventDefault();
  console.log('clicked on submit button.')
  const from = inputData.from;
  const to = inputData.to;
  const date = inputData.date;
  const ticketclassName = inputData.ticketclassName;
  const guests = inputData.guests;
  const id = parseInt(booked.state.length) + 1;

  const allData = { from, to, date, ticketclassName, guests, id }  
}
javascript reactjs arrays redux push
1个回答
3
投票

如果书的状态是一个数组,初始状态可能应该是一个空数组。然后,您可以浅复制数组并将新数据附加到它。

当你想删除一本书时,例如从数组中删除,使用

Array.prototype.filter
删除特定元素。

此外,默认情况应该只按原样返回当前/现有状态,并且not创建新的对象引用。这样,如果它没有更新,它就不会不必要地触发任何组件重新渲染。

const initialState = [];

const bookingReducer = (state = initialState, action) => {
  switch (action.type) {
    case NEWBOOK:
      return state.concat(action.payload);
      // or
      return [...state, action.payload];

    case DELETEBOOK:
      return state.filter(/* filter condition callback */);

    default:
      return state;
  }
}

如果你真的想使用

Array.prototype.push
那么它会像这样做:

case NEWBOOK:
  const newState = state.slice(); // shallow copy
  newState.push(action.payload);  // update copy
  return newState;                // return copy

这是因为

push
方法改变了它操作的数组。

© www.soinside.com 2019 - 2024. All rights reserved.