【问题标题】:use a variable in other component in Reactjs在 Reactjs 的其他组件中使用变量
【发布时间】:2020-02-29 07:04:52
【问题描述】:

我需要在其他组件中调用一些变量,这样我就可以在渲染条件下使用它(全局变量)

第一个组件代码:

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

【问题讨论】:

  • 据我了解,你必须使用redux
  • 能否在你想使用的组件中加入代码sn-p?另外,澄清一下,您是否打算通过react-router 重定向它?

标签: javascript reactjs state react-props


【解决方案1】:

你可以像这样将该变量传递给你想要重定向的页面

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

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

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

【讨论】:

  • 如果你想路由另一个组件,这个方法是正确的。如果您在子组件中使用,则将变量作为道具传递。
  • 是的..这是 React 的基本概念,您可以将父组件的变量作为 'props 传递给子组件。
【解决方案2】:

如果你要传递 props 的组件是这个组件的子组件,你需要使用 props 来传递它。 示例:

<ChildComponent roole={this.roole}/>

其他情况需要使用

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

要获得它,请使用:

this.props.location.state.roole

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-05
    • 1970-01-01
    • 1970-01-01
    • 2018-10-25
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多