在Reactjs的其他组件中使用变量

我需要在其他组件中调用一些变量,以便可以在有条件的渲染中使用它(全局变量)

第一个组件代码:

class Connexion extends Component {
    constructor (props) {
        super(props);
        this.state = {
            // name: "",cnx_mail: '',cnx_pwd: '',items: [],errors: {},redirection : false,formErrors: {cnx_mail: '',cnx_pwd: ''},emailValid: false,passwordValid: false,formValid: false
        }

        this.handleUserInput = this.handleUserInput.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
      }

    componentDidmount() { }

    handleSubmit = (event) => {
        event.preventDefault();
        fetch(`${API}/api/connexion`,{
            method: 'POST',headers: {
                'Content-Type': 'application/json',},body: JSON.stringify ({
                email: this.state.cnx_mail,password: this.state.cnx_pwd,})
        })
        .then(res => res.json())
        .then(json => {
            this.setState({ items: json.result });

            // console.log("jsooon: ",json);
            localStorage.setItem('head',json.result.split('.')[0]);
            localStorage.setItem('payload',json.result.split('.')[1]);
            localStorage.setItem('signature',json.result.split('.')[2]);

            var roole = JSON.parse(atob(json.result.split('.')[1])).account[0].role ;
            // this.setState({ therole : roole });
            if(roole=== 'admin') {
                console.log("role admin : ",roole);
                console.log(json.result);
                this.setState({ redirection: true })
                // this.context.router.push('/accounts');
                //   return <Redirect to='/accounts' />
                // this.props.history.push('/accounts')

            }
            else {
                console.log("is user");
            }
        })
    }
...

在这里,我必须获取"roole"的值,并在其render()中的另一个组件中调用它,并使其具有条件说

如果roole=="admin"显示div1,否则显示div2

ayufly 回答:在Reactjs的其他组件中使用变量

您可以像这样将变量传递到您要重定向的页面

this.props.history.push('/accounts',{roole})

// Access variable to redirected page
this.props.location.state.roole;`

另一种方法是,您可以将该角色存储到本地存储中,并从本地存储访问该值。

,

如果要传递道具的组件是该组件的子代,则需要使用道具将其传递下来。 示例:

<ChildComponent roole={this.roole}/>

在其他情况下,您需要使用

this.props.history.push({
  pathname: '/your_path',state: { roole: this.roole }
})

要获取它,请使用:

this.props.location.state.roole
本文链接:https://www.f2er.com/3169830.html

大家都在问