react-第四章-useReducer

73 阅读1分钟

useReducer:更适合处理复杂的状态逻辑。

useReducer 跟 useState 一样的都是帮我们管理组件的状态的,但是呢与useState不同的是 useReducer 是集中式的管理状态的。

购物车案例:

  let [data, dispatch] = useReducer(reducer, initData)
  return (
    <>
      <table cellPadding={0} cellSpacing={0} width={600} border={1}>
        <thead>
          <tr>
            <th>物品</th>
            <th>价格</th>
            <th>数量</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          {
            data.map((item) => {
              return (
                <tr key={item.id}>
                  <td align='center'>
                    {item.isEdit ? 
                      <input 
                        onBlur={e => dispatch({ type: "EDIT", id: item.id })} 
                        onChange={e => dispatch({ type: "UPDATE_NAME", id: item.id, newName: e.target.value })} 
                        value={item.name} 
                      /> 
                      : 
                      <span>{item.name}</span>
                    }
                  </td>
                  <td align='center'>{item.price * item.count}</td>
                  <td align='center'>
                    <button onClick={() => dispatch({ type: "SUB", id: item.id })}>-</button>
                    <span>{item.count}</span>
                    <button onClick={() => dispatch({ type: "ADD", id: item.id })}>+</button>
                  </td>
                  <td align='center'>
                    <button onClick={() => dispatch({ type: "EDIT", id: item.id })}>编辑</button>
                    <button onClick={() => dispatch({ type: "DELETE", id: item.id })}>删除</button>
                  </td>
                </tr>
              )
            })
          }
        </tbody>
        <tfoot>
          <tr>
            <td colSpan={3}></td>
            <td align='center'>总价:{data.reduce((prev, next) => prev + next.price * next.count, 0)}</td>
          </tr>
        </tfoot>
      </table>
    </>
  )
}