【问题标题】:UI not updating after userReducer changes stateuserReducer 更改状态后 UI 未更新
【发布时间】:2021-12-29 19:32:31
【问题描述】:

我正在尝试使用 reducer 函数来更新状态。我有一个状态变量,phones,它是一个 phone 对象数组。当用户单击一个按钮时,我希望电话对象的数量属性增加。数量确实增加了,但 UI 没有变化。

这是我的代码:

const initialState = {
  phones: [...Phones]
};

const reducer = (state, action) => {
  if (action.type === "increase") {
    const newPhones = state.phones.map(phone => {
      if (phone.id === action.payload) {
        return { ...phone, quantity: phone.quantity + 1 };
      }
      return phone;
    });
    return { ...state, phones: newPhones };
  }
};

const Cart = () => {
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <div className="cart_div">
      <h1>Your Bag</h1>
      {Phones.map(phone =>
        <PhoneListItem
          key={phone.id}
          dispatch={dispatch}
          state={state}
          {...phone}
        />
      )}
    </div>
  );
};

const PhoneListItem = ({ name, price, img, quantity, dispatch, id, state}) => {

  return (
    <div className="phone_row">
      <img className="phone_img" src={img} />
      <div className="phone_info_div">
        <h4>
          {name}
        </h4>
        <h4 className="price">
          {price}
        </h4>
      </div>
      <div className="phone_amount_div">
        //user clicks on button to increase phone quantity
        <button className="increase_button" onClick={() => dispatch({ type: "increase", payload: id })}>
          <Icon icon="akar-icons:chevron-up" />
        </button>
        <p className="phone_amount_para">{quantity}</p>
        <button className="decrease_button" onClick={() => dispatch({ type: "decrease", payload: id })}>
          <Icon icon="akar-icons:chevron-down" />
        </button>
      </div>
    </div>
  );
};

【问题讨论】:

  • Cart 尝试将{Phones.map(phone =&gt; 更改为{state.phones.map(phone =&gt;
  • 哇它现在可以工作了,但是为什么
  • 因为Phones 是从组件外部声明或导入的变量并且永远不会更新,而state.phones 是从useReducer 钩子返回的值,当您调度事件时它实际上会更新.

标签: reactjs react-hooks use-reducer


【解决方案1】:

useReducer 将返回整个状态而不是状态切片。

你已经通过数组解构得到了状态,但是你没有使用它。

const [state, dispatch] = useReducer(reducer, initialState);

{state.Phones.map(phone => {
  return <PhoneListItem
          key={phone.id}
          dispatch={dispatch}
          state={state}
          {...phone}
        />
})}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-15
    • 1970-01-01
    • 2020-09-03
    • 1970-01-01
    相关资源
    最近更新 更多