Node.js 使用Reactjs和Nodejs在变量中存储数据
我使用React和nodejs,我可以成功地检索数据,但无法将其存储在变量中Node.js 使用Reactjs和Nodejs在变量中存储数据,node.js,reactjs,Node.js,Reactjs,我使用React和nodejs,我可以成功地检索数据,但无法将其存储在变量中 OnSubmit(e){ const user={ email:this.state.email, password:this.state.password, } axios.post('http://localhost:5000/Users/login',user) .then(res=>(console.log(res.data
OnSubmit(e){
const user={
email:this.state.email,
password:this.state.password,
}
axios.post('http://localhost:5000/Users/login',user)
.then(res=>(console.log(res.data)))//want to store this res.data in a variable
localStorage.setItem("token","got")
this.setState({
loggedin:true
})
就这样:
let userDetails = null;
axios.post('http://localhost:5000/Users/login',user)
.then(res=>{userDetails = res.data})
但是,如果您想在异步调用之外使用它,那么userDetails的值将为null,因为这是一个异步获取,所以您可以在.then()内的状态中设置此值,如下所示
axios.post('http://localhost:5000/Users/login',user)
.then(res=>{this.setState({userDetails: res.data})})
在arrow函数中,Paranethesis
()
具有隐式返回语句,并且只能包含单个语句。然而,大括号{}
需要显式的返回语句,您可以在范围内添加多个语句
axios.post('http://localhost:5000/Users/login',user)
.then(res=> {
// Here, you can do required manipulation of data returned from promise
console.log(res.data)
localStorage.setItem("token","got")
this.setState({ loggedin:true })
})
您可以将其应用于变量、React状态(类组件)或挂钩。有多种方式可供选择: 基于类的组件: 轴心柱http://localhost:5000/Users/login,用户)
然后(res=>this.setState({data:res.data}))在状态中定义一个变量,比如“userData:null”; 那么这样做,
axios.post('http://localhost:5000/Users/login',user)
.then(res=>{
// try to console.log `res` and checkout its hierarchy.
this.setState({userData: res.data});
})
你可以用这个
axios.post('http://localhost:5000/Users/login',user)
.then(res=>{this.setState({userDetails: res.data})})
我已经将数据保存在一个变量中,比如axios.post(')。然后(res=>{Userdata=res.data.users console.log(Userdata)console.log(Userdata.u id)}),但是如果(this.state.loggedin){return},我无法在render()函数中使用它它给了我一个错误类型错误:无法读取未定义的属性“\u id”要在渲染中使用它,您应该按照我在回答中提到的状态设置此值,然后像这样使用它:如您所说的那样尝试,但它仍然给我相同的错误尝试记录userDetails,可能它没有\u id,或者,如果要将其存储在本地存储中,则无需将其设置为状态