【问题标题】:Passing in Redux state to React Component将 Redux 状态传递给 React 组件
【发布时间】:2018-07-08 03:46:41
【问题描述】:

我正在使用react-redux 在我的应用程序中获得更流畅的数据流。 在我的LoginPage 组件中,为了简单起见,我使用纯组件。

const LoginPage = ({ auth, doLogin, doLogout }) => (

    <div>
      <NavBar auth={auth}/>
        <div className="row">
            <div style={{display: 'flex', justifyContent: 'center'}} className="col-md-4 col-md-offset-4">
                <LoginForm auth={auth} doLogin={doLogin} doLogout={doLogout}/>
            </div>
        </div>
      </div>

);

// Connects state to the props of this component
const mapStateToProps = state => ({
  auth: state.auth,
});

// Return a NEW component that is connected to the Store
export default connect(mapStateToProps, { doLogin, doLogout })(LoginPage);

这完全符合我的预期,但我尝试更改格式以不使用纯组件,因为我想做条件渲染(登录时显示不同的组件)。

现在看起来如下:

const LoginComponent = ({ auth, doLogin, doLogout }) => (

    <div>
      <NavBar auth={auth}/>
        <div className="row">
            <div style={{display: 'flex', justifyContent: 'center'}} className="col-md-4 col-md-offset-4">
                <LoginForm auth={auth} doLogin={doLogin} doLogout={doLogout}/>
            </div>
        </div>
      </div>

);

class LoginPage extends React.Component {
    constructor(props) {
        super(props);
    }
    render() {
        return (
            <LoginComponent/>
        )
    }
}

我将LoginPage 更改为LoginComponent 并尝试在实际的React 组件中呈现LoginComponent。

但是,这给了我一个错误,说Cannot read property 'isLoggedIn' of undefined。 isLoggedIn 是 auth 的一个元素。

在我的第一个示例中,我可以通过 const LoginPage = ({ auth, doLogin, doLogout }) 传入auth,但是当我更改为第二个示例时,我不确定如何传入auth。

我该怎么做?

【问题讨论】:

    标签: javascript reactjs redux


    【解决方案1】:

    将 props 传递给无状态的功能组件,就像使用任何其他 React 组件一样。现在道具没有被传递给LoginComponent,所以它们将永远是undefined。

    class LoginPage extends React.Component {
        constructor(props) {
            super(props);
        }
        render() {
            return (
                <LoginComponent
                  auth={this.props.auth}
                  doLogin={this.props.doLogin}
                  doLogout={this.props.doLogout}
                />
            )
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-01-26
      • 2016-11-26
      • 1970-01-01
      • 2016-08-31
      • 1970-01-01
      • 2021-03-08
      • 2019-01-20
      • 2022-01-18
      • 2019-09-18
      相关资源
      最近更新 更多