reducer返回null(使用路由器和参数来响应redux)

时间:2020-06-16 16:20:25

标签: reactjs redux react-redux react-router

我有一个简单的商店,在reducer上有一个getall和getbyid

const initstate = {
   allobjects: [],
   object: {}
}

switch (action.type) {
    case Constant.GET_OBJECT:
      const object = state.allobjects.find(o => o.id === action.payload)
      return {
         ...state,
         object
      }
    case Constant.GET_ALL:
      const allobjects = action.payload
      return {
          ...state,
          allobjects
      }
}

我有两个组成部分:

// ObjectsList

export const ObjectList = ({ objects}) => {

  useEffect(() => {
      // execute action to getobjects
    }, []) 
  return (
    <>
      {
        objects.map(o => > { <div>o.name</div>})
      }
    </>
  )
}

// mapstatetoprops return objects from init state
// mapdispatchtoprops that calls getobjects

export default connect(ObjectsList);


// Object

const Object = () => {
   const { obj_id } = userParams()
   useEffect(() => {
      // execute action to getobjbyid
    }, [])

   return (<div>selected {obj.name}</div>)
}

// mapstatetoprops return obj from init state
// mapdispatchtoprops that calls getobjectbyid

export connect(Object);

然后我用我的反应路由器dom在身体的这两个组件之间切换。

const Container = () => {
  return (
     <>
         <Router exact path='/' component={ObjectsList} />
         <Router exact path='/:obj_id' component={Object} />
     </>
  )
}

如果我到达路径“ /”,我将拥有对象列表,但是如果我到达“ /:obj_id”路径,它将把我的对象属性(从初始化状态)设置为null / [ ]。唯一不会成为null的方法是,如果我访问'/'路由并在应用程序上具有一个链接来触发'/:obj_id'路由。

我的问题是,直接进入/ obj_id路由而不必从objectslist组件加载对象列表的最佳方法是什么?

1 个答案:

答案 0 :(得分:-1)

首先,订阅redux是错误的。 实际语法:connect()(Object)

第二个reducer语法错误,语法正确:

YourReducer = (state = initialState, { type, data }) => {
      switch (action.type) {
         case Constant.GET_OBJECT:
           const object = state.allobjects.find(o => o.id === action.payload)
           return {
              ...state,
              object
           }
         case Constant.GET_ALL:
           const allobjects = action.payload
           return {
             ...state,
             allobjects
           }
         default: return state
     }
}

第三名:

使用CombineReducer创建Redux状态,正确的语法:

return combineReducer({
   myState: YourReducer
})

完成上述所有操作后,您就可以使用redux的好处。