Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.7k views
in Technique[技术] by (71.8m points)

useReducer应该怎样合理写?

第一种:

const reducer = (state, action) {
  const { type, payload } = action;
  switch(type) {
    case 'list':
      return { ...state, ...payload };
    default: 
    return state;
  }
}
//ui

 <div>
    <button onClick={()=>{dispach({type:'list',payload:{list:state.list.concat(1)})}}>尾部添加</button>
    <button onClick={()=>{dispach({type:'list',payload:{list:[1].concat(state.list)})}}>头部添加</button>
 </div>

第二种:

const reducer = (state, action) {
  const { type, payload } = action;
  switch(type) {
    case 'push':
      return { ...state, list:state.list.concat(1)};
    case 'unshift':
      return {...state,list:[1].concat(state.list)}
    default: 
    return state;
  }
}
//ui
   dispach({type:'push'}) 
   //dispach({type:'push',payload:{value:1}})
   dispach({type:'unshift'})

看到别人很多代码使用会第一种,逻辑没有写在reducer里.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

我觉得两种都没问题吧,reducer你把它当作一个纯函数,只维护一个非常确定的操作结果,比如你 push,就是往后添加一个元素,不需要做别的事情,那么我认为,你可以dispatch('push', pushItem), 真正push的操作 交给reducer处理,如果说push的过程中有副作用,比如你push完了你要去获取 push之后的长度,然后做其他事情,很显然这个操作放在reducer里面操作的话,会让你的reducer操作变的不纯,这会导致代码很难维护,要么就是push完了之后在useEffect里面去进行后面的操作,这回导致逻辑分散。 所以写怎么写都可以,但是有些约束会让你决定到底写在哪里


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...