代码之家  ›  专栏  ›  技术社区  ›  Nicolas S.

在组件创建之前等待道具(而不是渲染)

  •  0
  • Nicolas S.  · 技术社区  · 6 年前

    在创建应用程序的任何组件之前,我必须调用personal端点来接收用户数据(例如,关于他是否是管理员)。

    我现在有这样的东西:

    export default class Recrutement extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
            // some data
          };
        }
        
        // A lot of functions
        
        columnDefs = [{
                //A lot of variable
                width: ((this.props.user === null) ? 50 : ((this.props.user.columnDefinitions.find(function (v) { return v.colId === 0 }) || {}).size)),
                //some functions
            },
            {
                //A lot of variable
                width: ((this.props.user === null) ? 50 : ((this.props.user.columnDefinitions.find(function (v) { return v.colId === 1 }) || {}).size)),
                //some functions
            }]
    }
    
    class App extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                api: new ApiService(),
                user: null
            };
        }
    
        componentWillMount() {
            this.getUser();
        }
    
        getUser = async () => {
            let getUserInfo = (json) => {
                this.setState({
                    api: this.state.api,
                    user: json
                });
            };
            if (this.state.api.isLoggedIn()) this.state.api.getUserInfo(getUserInfo);
            else this.setState(this.state);
        }
        
    
        render() {
            if (this.state.api.isLoggedIn()) {
                return (
                    <div className="mainApp">
                        <Recrutement user={this.state.user} />
                    </div>
            )}
            else
            return (
                <div>
                    <Login connexion={this.getUser} />
                </div>
            );
        }
    }
    
    
    ReactDOM.render(
        <App />,
        document.getElementById('app')
    );
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
    
    <div id="app" />

    如您所见,我正在使用prop设置数组中的一些数据(ag grid columns definitions)。或者在render()之前初始化此数组。 我的目标是在初始化所有内容之前让prop.user准备好(而不是空的)。

    有人知道怎么做吗?

    0 回复  |  直到 6 年前