【问题标题】:React pass props to children edge case?将传递道具反应到儿童边缘案例?
【发布时间】:2018-07-27 00:19:41
【问题描述】:

我的应用程序具有以下结构,我想将基于 Header 状态的道具传递给 RT 组件。我可以使用 Context 轻松传递它,但是当 prop 为某个值时我需要调用 API,并且 Context 似乎不是为此用途而设计的,因为它使用了渲染模式。

在 Header.js 中,我使用 this.props.children 渲染孩子。为了传递道具,我尝试了以下模式,但没有任何效果。我在这里缺少一个概念。这是什么?

(1) React.Children.map(children, child =>
      React.cloneElement(child, { doSomething: this.doSomething }));

(2) {React.cloneElement(this.props.children, { loggedIn: this.state.loggedIn })}

(3) <Route
      path="/issues"
      render={({ staticContext, ...props }) => <RT {...props} />}
    />

结构:

App.js

<Header>
  <Main />
</Header>

Main.js

const Main = () => (
  <Grid item xl={10} lg={10}>
    <main>
      <Switch>
        <Route exact path="/" component={RT} />
        <Route path="/projects" component={Projects} />
        <Route path="/issues" component={RT}/>
        <Route path="/notes" component={Notes} />
      </Switch>
    </main>
  </Grid>
);

【问题讨论】:

    标签: javascript reactjs react-router


    【解决方案1】:

    我个人建议使用 React Context API 来处理用户状态,而不是通过 props 手动传递它。这是我如何使用它的示例:

    import React from 'react';
    
    export const UserContext = React.createContext();
    
    export class UserProvider extends React.Component {
        constructor(props) {
            super(props);
    
            this.state = {
                user: false,
                onLogin: this.login,
                onLogout: this.logout,
            };
        }
    
        componentWillMount() {
            const user = getCurrentUser(); // pseudo code, fetch the current user session
            this.setState({user})
        }
    
        render() {
            return (
                <UserContext.Provider value={this.state}>
                    {this.props.children}
                </UserContext.Provider>
            )
        }
    
        login = () => {
            const user = logUserIn(); // pseudo code, log the user in
            this.setState({user})
        }
    
        logout = () => {
            // handle logout
            this.setState({user: false});
        }
    }

    然后您可以在任何需要的地方使用 User 上下文,如下所示:

    <UserContext.Consumer>
        {({user}) => (
            // do something with the user state
        )}
    </UserContext.Consumer>

    【讨论】:

    • 这个问题是我需要调用一个基于 Context 值的 API,而你不能用 context 来做,因为它使用的是渲染模式。
    • 我做同样的事情,使用 firebase 身份验证。您可以访问所有与组件相同的生命周期事件。如果您需要将上下文作为道具访问,您可以创建一个传递上下文的高阶组件,如下所示:github.com/forrestLyman/dig-framework/blob/master/src/lib/core/…
    • 谢谢,这看起来很有希望,我试试看。
    猜你喜欢
    • 1970-01-01
    • 2020-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多