Javascript 如何防止在渲染新组件时重置react状态
我正在我的react web应用程序中执行用户身份验证。我通过调用数据库检索用户数据,然后通过props将用户数据传递给父组件。我的目标是将该数据设置为父级的状态,以便将其发送回另一个子级。下面是我用来检索用户数据并将其发送到父组件的代码:Javascript 如何防止在渲染新组件时重置react状态,javascript,reactjs,react-router,components,react-props,Javascript,Reactjs,React Router,Components,React Props,我正在我的react web应用程序中执行用户身份验证。我通过调用数据库检索用户数据,然后通过props将用户数据传递给父组件。我的目标是将该数据设置为父级的状态,以便将其发送回另一个子级。下面是我用来检索用户数据并将其发送到父组件的代码: validateUser = (event) => { event.preventDefault(); fetch('http://localhost:8080/signIn/?username=' + this.state.validateUsern
validateUser = (event) => {
event.preventDefault();
fetch('http://localhost:8080/signIn/?username=' + this.state.validateUsername + '&password=' + this.state.validatePassword,
{
method: 'GET',
headers: new Headers({
'Access-Control-Allow-Origin': 'http://localhost:8080/'
})
}
)
.then((response) => response.json())
.then((response) => {
console.log('testing' + response.businessName)
if (response.userID === undefined) {
console.log('user does not exist')
} else {
console.log('hello world testing' + response)
this.props.currentUserID(response.userID);
this.props.password(this.state.validatePassword);
this.props.employeeStatus(response.employeeStatus);
this.props.businessName(response.businessName);
if (response.employeeStatus === 'M') {
window.location = 'http://localhost:3000/ManagerDashboard';
} else if (response.employeeStatus === 'E') {
window.location = 'http://localhost:3000/EmployeeDashboard'
}
}
})
}
setCurrentUserID = (data) => {
console.log('TESTING SET CURRENT USER ID YOYOYOYOYOYOYOYOYOYOYOYOYOYOYOYOYOYOYOYO');
console.log(data);
this.setState({ myID: data });
}
下面是我在父组件中将数据设置为状态的代码:
validateUser = (event) => {
event.preventDefault();
fetch('http://localhost:8080/signIn/?username=' + this.state.validateUsername + '&password=' + this.state.validatePassword,
{
method: 'GET',
headers: new Headers({
'Access-Control-Allow-Origin': 'http://localhost:8080/'
})
}
)
.then((response) => response.json())
.then((response) => {
console.log('testing' + response.businessName)
if (response.userID === undefined) {
console.log('user does not exist')
} else {
console.log('hello world testing' + response)
this.props.currentUserID(response.userID);
this.props.password(this.state.validatePassword);
this.props.employeeStatus(response.employeeStatus);
this.props.businessName(response.businessName);
if (response.employeeStatus === 'M') {
window.location = 'http://localhost:3000/ManagerDashboard';
} else if (response.employeeStatus === 'E') {
window.location = 'http://localhost:3000/EmployeeDashboard'
}
}
})
}
setCurrentUserID = (data) => {
console.log('TESTING SET CURRENT USER ID YOYOYOYOYOYOYOYOYOYOYOYOYOYOYOYOYOYOYOYO');
console.log(data);
this.setState({ myID: data });
}
我已经确定数据通过得很好,事实上数据也被正确设置为state。这就是我认为给我带来麻烦的问题。在子组件中设置道具后,我使用window.location语句渲染一个新组件。这将使用父组件中的react router dom呈现特定组件。似乎在渲染新组件时,父状态被重置。但是,我需要将这些数据保持设置为state,以便将其传递回不同的子级。我以前将此数据设置为本地存储;然而,因为它是用于用户身份验证的,所以这是一种不安全的方法。如何将此数据设置为状态并防止其重置,即使在渲染新组件时也是如此?我真的很感激任何想法