我需要在其他组件中调用一些变量,以便可以在有条件的渲染中使用它(全局变量)
第一个组件代码:
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