【问题标题】:How can I change the state of App.js from a form treatment?如何从表单处理中更改 App.js 的状态?
【发布时间】:2020-10-28 22:03:25
【问题描述】:

我的 App.js 包含我的路由器和我的路由。我有一条到我的 Home 组件的路由和一条到我的 LoginForm 组件的路由。

在我的 LoginForm 中,我使用 axios(调用 API)进行身份验证。我将用户存储在本地存储中并重定向到我的 Home 组件。

在我的 App.js 中,我的状态中有一个布尔值 isLoggedIn。在componentDidount 中,我检查本地存储中是否有东西来更新我的状态。如果不刷新页面,我找不到更改状态的方法。

我应该怎么做才能从我的 LoginForm 组件更新 App.js 中的状态?

App.js

class App extends Component {
    componentDidMount() {
        let state = localStorage["appState"];
        if (state) {
            let AppState = JSON.parse(state);
            this.setState({ isLoggedIn: AppState.isLoggedIn,user: AppState.user });
        }
    }
    render() {
        return (
            <Router>
                <div className="App">
                    <Route path="/" exact component={BatteryUp} />
                    <Route path="/login" exact component={LoginForm} />
                </div>
            </Router>
        );
    }
}

LoginForm -> axios 然后渲染

.then(response => {
    let appState = { isLoggedIn: true, user: userData };
    localStorage.setItem("appState",JSON.stringify(appState));
    this.setState({ redirect: true });
}

render() {
    if (this.state.redirect) {
        return <Redirect to="/" />;
    }
    return (
        <form className="container" onSubmit={this.handleFormSubmit}>
        </form>
    );
}

【问题讨论】:

    标签: reactjs react-router axios react-router-dom


    【解决方案1】:

    这通常是 redux 的用途。您将在 redux 中更新状态,然后对 reducer 的更新将传播到 App。另一种解决方案是将所有这些逻辑包含在 APP 组件中。这不会使事情变得非常模块化。

    【讨论】:

      猜你喜欢
      • 2016-08-04
      • 1970-01-01
      • 2019-08-28
      • 2022-12-18
      • 1970-01-01
      • 1970-01-01
      • 2013-03-28
      • 2017-07-30
      • 2022-11-25
      相关资源
      最近更新 更多