javascript - 在 React 中使用 window.location.reload 是否正确?

标签 javascript reactjs redux

当您打开reactjs.org时在“声明性”标题下,有一句话:当数据发生变化时,React 将有效地更新和渲染正确的组件。

对于我的几个应用程序,我使用以下结构: 应用程序 | AppContainer(所有应用程序逻辑,在登录前受到保护) |登录(登录表单)

如果您根据用户的凭据在应用程序的 render 内返回 2 个不同的组件,则此结构效果很好。

render(){
   if(isUserLoggedIn()){
       return <AppContainer />;
   }

   return <Login />;
}

Login 组件内,我使用 window.location.reload 刷新页面,以便触发应用程序的 render,并且我将获取 AppContainer 组件。

但感觉有点像 jQuery + Angular。是否有更好(更 React)的方式来触发渲染函数,或者事情应该是这样的?

最佳答案

Is there a better(more React) way to trigger render function...

通常的方法是拥有状态,在本例中至少是一个 bool 值,表示用户是否登录,并在用户成功登录或注销时更新该状态。更新状态会触发渲染。

就您而言,由于您使用的是 Redux,因此您的状态可能会在那里。

我还没有使用 Redux,这大概是没有 Redux 时的样子(如果你使用的是类组件,就像你看起来的那样):

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            loggedIn: /*...initial value, perhaps from web storage or cookie...*/;
        };
        this.onLogin = this.onLogin.bind(this);
        this.onLogout = this.onLogout.bind(this);
    }

    onLogin() {
        // ...probably stuff here, then:
        this.setState({loggedIn: true});
    }

    onLogout() {
        // ...probably stuff here, then:
        this.setState({loggedIn: false});
    }

    render() {
        if (this.state.logedIn) {
            return <AppComponent onLogout={this.onLogout}/>;
        }
        return <Login onLogin={this.onLogin}/>;
    }
}

或者用钩子(Hook):

const App = () => {
    const [loggedIn, setLoggedIn] = useState(/*...initial value, perhaps from web storage or cookie...*/);

    const onLogin = useCallback(() => {
        // ...probably stuff here, then:
        setLoggedIn(true);
    }, [loggedIn]);

    const onLogout = useCallback(() => {
        // ...probably stuff here, then:
        setLoggedIn(false);
    }, [loggedIn]);

    if (this.state.logedIn) {
        return <AppComponent onLogout={onLogout}/>;
    }
    return <Login onLogin={onLogin}/>;
}

(再次粗略地)

关于javascript - 在 React 中使用 window.location.reload 是否正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58657054/

相关文章:

javascript - Redux-saga 不等待 API 的响应

javascript - 类型错误 : this. getResults(...) 未定义

javascript - 如何用 jQuery 做汽车转向灯(信号灯)?

reactjs - 元素类型无效 : expected a string (for built-in components), 我的导入方式似乎不错

javascript - 仅当当前未聚焦时如何聚焦元素?

javascript - 在回调中调用 yield,redux saga 给了我一个异常为什么?

javascript - 这是一个有效的递归函数吗?

javascript - 如何忽略来自其他域链接的脚本的 TrackJS 错误?

javascript - 访问 div 内的元素

javascript - 在 script 标签中包含 React 的 jsx 文件会出现错误