簡體   English   中英

無法更新我的應用程序的狀態,reducer 中的 console.log 顯示對象已更改,但狀態保持不變

[英]Unable to update the state of my app, console.log inside reducer shows that object has changed, but the state remains same

玩 redux 讓我很困惑。 一些如何更新對象中僅一個鍵的狀態變得如此困難的原因。

當用戶選中組件內的復選框時,將分派一個操作。 當它被檢查時,產品的狀態應該從 NEW 變為 RESERVED:

// ProductRow.js

const ProductRow = React.createClass({
  propTypes: {
    item: PropTypes.object.isRequired,
    onChange: PropTypes.func.isRequired
  },

  render () {
    const { code, name, imageUrl, description } = this.props.item.product
    const {status} = this.props.item
    const {onChange} = this.props
    return (
      <div>
        <label htmlFor={code}>
          <input type='checkbox' id={code} onClick={onChange} value={status} />
          <img src={imageUrl} />
          <div className='name'>{name}</div>
          <div className='description'>{description}</div>
        </label>
      </div>
    )
  }
})

ProductRow 的父組件是 ProductList:

const ProductList = React.createClass({

  propTypes: {
    items: PropTypes.array.isRequired,
    dispatchSetStatusToReservedForItem: PropTypes.func
  },

  handleProductCheckBoxClick (item) {
    if (document.getElementById(item.product.code).checked) {
      this.props.dispatchSetStatusToReservedForItem(item)
    }
  },

  render () {
    const {items} = this.props
    return (
      <div>
        {
          items.map((item) => {
            return (
              <ProductRow key={item.id} onChange={this.handleProductCheckBoxClick.bind(this, item)} item={item} />
            )
          })
        }
      </div>
    )
  }
})

當復選框被勾選時,我會收到 reducer 內部的 console.log 警報,它顯示了正確的輸出,即數組“item”中的正確對象已更改,但不知何故它沒有反映在 UI 和 rect 開發人員工具中.

//Reducer const DEFAULT_STATE = { shoppingCartData: shoppingCartData }

const setStatusToReserved = (state, action) => {
  const {items} = state.shoppingCartData.data

  items.map(item => {
    if(action.item.id === item.id) {
      console.log(Object.assign({},action.item, {status: 'RESERVED'}))
      return Object.assign({}, action.item, {status: 'RESERVED'})
    }
  })
}

const rootReducer = (state = DEFAULT_STATE, action) => {
  switch (action.type) {

    case ACTIONS.SET_STATUS_TO_RESERVED:
      return setStatusToReserved(state, action)

    default:
      return DEFAULT_STATE
  }
}

export default rootReducer

如果更改狀態的一部分,則需要為狀態創建新的對象引用。 按照您的方式,您的舊狀態仍將===新狀態,因此 redux 無法知道它已更改。

此外,您的setStatusToReserved函數根本不返回任何內容!

你的狀態不應該像現在這樣嵌套很深,我認為還有更多的工作要做,但向前邁出的一步是:

const setStatusToReserved = (state, action) => {
  const {items} = state.shoppingCartData.data

  const newItems = items.map(item => {
    if(action.item.id === item.id) {
      console.log(Object.assign({},action.item, {status: 'RESERVED'}))
      return Object.assign({}, action.item, {status: 'RESERVED'})
    }
  })

  return {
    ...state,
    shoppingCartData: {
      ...shoppingCartData.data,
      items: newItems
    }
  }
}

我強烈建議觀看免費並解決所有這些問題的Egghead Redux 系列

我大大簡化了減速器,我只從商店獲取狀態(通過設置初始狀態),我想更改並將產品列表設為我的智能組件(因為這是我唯一想要更改狀態的組件) . 我認為我對 reducer 所做的更改和仔細挑選了我的智能組件有所幫助。 感謝視頻推薦,Dan 的視頻幫助很大。

import { ACTIONS } from './actions'

/**
 * Returns an updated array with check product status set to RESERVED
 * @param state
 * @param action
 * @return {[*,*,*]}
 */
const setStatusToReserved = (state, action) => {
  let updateStatus = Object.assign({}, action.item, {status: 'RESERVED'})
  let index = state.indexOf(action.item)

  return [...state.slice(0, index), updateStatus, ...state.slice(index + 1)]
}

/**
 * Returns an updated array with check product status set to NEW
 * @param state
 * @param action
 * @return {[*,*,*]}
 */
const setStatusToNew = (state, action) => {
  let updateStatus = Object.assign({}, action.item, {status: 'NEW'})
  let index = state.indexOf(action.item)

  return [...state.slice(0, index), updateStatus, ...state.slice(index + 1)]
}

/**
 * Function that takes the current state and action and return new state
 * Initial state is set to product items
 * @param state
 * @param action
 * @return {{}}
 */
const rootReducer = (state = {}, action) => {
  switch (action.type) {
    case ACTIONS.SET_STATUS_TO_RESERVED:
      return setStatusToReserved(state, action)

    case ACTIONS.SET_STATUS_TO_NEW:
      return setStatusToNew(state, action)

    default:
      return state
  }
}

export default rootReducer
[PROD_FORM_DETAILS_SUCCESS]: (state, { payload: { ProdDetailsData } }) => 
        {
            console.log(" reducer ===================== " , catalogueProductDetailsData);
        return {
      ...state,
      catalogueProductDetailsData,
      isFetching: false,
    }},

[CREATE_USER_FORM]: (state, {}) => {
      console.log(" reducer =======CREATE_USER_FORM ============== ");
      return {
        ...state,
        isFetching: false,
      };
    },

   //Without console

    [CREATE_USER_FORM]: (state, {}) => ({
      ...state,
      isFetching: true,
    }),

暫無
暫無

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

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