gpt4 book ai didi

reactjs - 如何将更新的数据获取到 React 的构造函数中

转载 作者:行者123 更新时间:2023-12-03 14:31:44 26 4
gpt4 key购买 nike

// parent class
export default class HomeScreen extends React.Component {
constructor(props){
super(props);
this.state = {
password: '',
username:'',
session: 'mani',
};
}

authentication(){
const self = this;
axios.post('/api/users/login/', {
password: this.state.password,
username: this.state.username
})
.then(function (response) {
console.log(response);
var sessionid=response.headers["set-cookie"][0].split('Secure,').pop().split(';').shift();
self.setState({session: sessionid });
})
.catch(function (error) {
console.log("Invalid username/password");
});
}

render(){
return(<Session sessid={this.state.session}/>);
}
}

export default class Session extends Component {
constructor(props){
super(props);
this.sessionVariable = this.props.sessid;
}

render(){
console.log(this.props.sessid); // here i am getting updated value
console.log("constructor "+this.sessionVariable); // here i can't able to get updated value
return (<View></View>);
}
}

//child class
import React, { Component } from 'react'
import { View, Text } from 'react-native'

export default class Session extends Component {
constructor(props){
super(props);
this.state = {
sessid: this.props.sessid
}
}

componentWillReceiveProps(nextProps){
const { sessid } = nextProps;

if (sessid !== this.state.sessid) {
this.setState({sessid});
}
}

render(){
console.log(this.props.sessid);
console.log("dummy"+this.state.sessid);

return (<View></View>);
}
}

如何在 React 中将更新的数据获取到构造函数中你能给我快速的解决方案吗我需要更新 constructor 中的数据。然后只有我能够在所有组件中调用全局变量

如何在 React 中将更新的数据获取到构造函数中你能给我快速的解决方案吗我需要更新 constructor 中的数据。然后只有我能够在所有组件中调用全局变量

最佳答案

在状态中添加您的 props 值,并使用 componentWillReceiveProps '生命周期更新它。

constructor(props) {
super(props);
this.state = {
sessid: this.props.sessid;
};
}

componentWillReceiveProps(nextProps){
const { sessid } = nextProps;
if(sessid !== this.state.sessid) {
this.setState({sessid});
}
}

关于reactjs - 如何将更新的数据获取到 React 的构造函数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49529126/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com