【发布时间】: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