Redux 函数 "connect" 在无状态组件中分配了错误的状态值

Redux function "connect" assigns wrong state value in statless component

我正在尝试将一些道具传递给无状态组件以满足我的条件渲染需求。当像 var: state.reducer.var 这样的 connect() 中为我的变量分配 redux 状态值时,我没有得到 "state.reducer.var" 对象。相反,我得到了整个状态对象。

console.log(state.reducer.var) 在 connect() 作为回调时,我得到了预期的结果 - var 值。但是,当 console.log(var) 作为回调将我新分配的 var 传递给它时,我得到了一个对象,当 console.log(state).

在我的子组件中,我得到 undefined using my var as props.var

const _ProtectedRoute = ({ component: Component, ...rest }, props) => {
  return (
    <Fragment>
      {!props.isAuthed
        ? <Redirect to="auth" noThrow />
        : <Component {...rest} />
      }
    </Fragment>
  );
}

const ProtectedRoute = connect(
  (state) => ({
    isAuthed: state.user.isAuthed,
  }, (isAuthed) => {console.log('state value: ', isAuthed)})
)(_ProtectedRoute);

我希望我分配 redux 状态的 var 作为 prop 传递给我的无状态 _ProtectedRoute 组件,这样我就可以在条件语句中使用它。

你做的一切都正确,它应该按预期工作,但我确实注意到你的代码中存在语法问题,连接的第一个参数中的大括号后应该有一个右括号,第二个参数也应该 return 一个对象,如下所示

const ProtectedRoute = connect(
  (state) => ({
    isAuthed: state.user.isAuthed,
  }), (dispatch) => ({
      printAuth:(isAuthed) => {console.log('state value: ', isAuthed)}
  })
)(_ProtectedRoute);

我对函数参数缺乏了解是问题所在。 我的 connect() 功能确实有效(应该有效)。在我的子组件中接收道具时出现问题。 ({ component: Component, ...rest }) 已经是 "The props"。 ({ component: Component, ...rest }, props) 意味着我分配了另一个未定义的 "props" 参数。 因此,与其将 component 转换为 Component 以便稍后在我的函数中用作 <Component />,不如稍后在 return() 之前完成。它导致像往常一样将道具作为参数传递。因此,我的子组件现在可以从 mapStateToProps().

接收 redux 状态作为道具

P.S。正如一些人提到的那样,connect() 中的控制台登录确实是错误的,因为它不是回调。

const _ProtectedRoute = props => {
  const Component = props.component;
  return (
    <Fragment>
      {!props.isAuthed
        ? <Redirect to="auth" noThrow />
        : <Component {...props} />
      }
    </Fragment>
  );
}

const mapStateToProps = (state) => ({
  isAuthed: state.user.isAuthed
});

const ProtectedRoute = connect(mapStateToProps, null)(_ProtectedRoute);