如何防止在渲染新组件时重置反应状态

时间:2021-04-16 02:23:43

标签: javascript reactjs react-router components react-props

我正在我的 React Web 应用程序中执行用户身份验证。我通过调用我的数据库来检索用户数据,然后通过 props 将用户数据传递给父组件。我的目标是然后将此数据设置为父母的状态,以便我可以将其发送回另一个孩子。这是我用来检索用户数据并将其发送到父组件的代码:

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 });

}

我已经确定数据传递得很好,实际上数据也被正确设置为状态。这是我认为给我带来麻烦的问题。在子组件中设置 props 后,我使用 window.location 语句渲染一个新组件。这会在我的父组件中使用 react-router-dom 呈现一个特定的组件。似乎随着新组件的渲染,父状态被重置。但是,我需要这些数据保持设置状态,以便向下传递给不同的孩子。我之前将这些数据设置到本地存储;但是,由于它用于用户身份验证,因此这是一种不安全的方法。即使在渲染新组件时,如何将这些数据设置为 state 并防止其重置?我真的很感激任何想法!!!

0 个答案:

没有答案