javascript - React Context API 和子组件刷新
问题描述
我有一个 Context 组件,当我设置某个值时,我希望它们影响使用它的其他组件,但我的理解在这里似乎是错误的。
我有一个主要处理屏幕布局的 MainComponent 组件。
import { Consumer } from './context';
class MainContainer extends React.Component {
render() {
const noPadding = {
margin: 0,
padding: 0
}
const isAuthenticated = this.context.isAuthenticated()
return (
<HashRouter>
<Header />
<Container>
{isAuthenticated &&
<AuthorisedArea>
<Row style={noPadding}>
<Col md="3" style={noPadding}>
<RightInfoBar />
</Col>
<Col md="9">
<RouteManager />
</Col>
</Row>
</AuthorisedArea>
}
</Container>
</HashRouter>
)
}
}
MainContainer.contextType = Consumer;
export default MainContainer
当用户登录时,这一切都应该起作用。当他们注销时,现在,我真的希望看到一个空白屏幕。
在我的导航栏中,当用户单击注销时,我会这样做:
handleLogout() {
const { toastManager } = this.props;
const { pathname } = this.props.location;
this.context.changeAuthenticated(false);
this.context.logout();
if(pathname !== "/") {
this.props.history.push("/");
}
toastManager.add('You\'re now logged out', {
appearance: 'success',
autoDismiss: true,
pauseOnHover: false,
});
}
更新我的上下文组件中的this.context.logout
属性,将“isAuthenticated”设置为 false。
所以我的基本上下文组件:
const Context = React.createContext();
export class Provider extends React.Component {
state = {
user: {
name: "",
email: "",
authStatus : Auth.isAuthenticated()
},
changeEmail: (newEmail) => {
let user = this.state.user;
user.email = newEmail;
this.setState({ user: user})
},
changeAuthenticated: (newState) => {
if(newState ===false) Auth.logout();
let user = this.state.user;
user.name = "Craig";
this.setState ({ user: user });
},
logout: () => {
console.log("Will logout");
Auth.logout();
this.setState({authStatus: false});
},
isAuthenticated: () => {
return Auth.isAuthenticated()
}
}
render() {
return (
<Context.Provider value={this.state}>
{this.props.children}
</Context.Provider>
)
}
}
export const Consumer = Context.Consumer;
所以,我希望我的主要组件会注意到 isAuthenticated 变为假......并且屏幕会变成空白(现在......一旦我有这个工作,我会做更好的事情)。
但是当我单击注销时 - 控制台指示 Context 组件中的方法被触发......并且值变为假......但屏幕仍然存在。
只有当我按 F5 时,屏幕才会按预期运行。
我应该如何MainComponent
对 React.Context 值更改做出反应?
解决方案
推荐阅读
- ubuntu - 按特定顺序格式化文本行 - 终端
- timer - 使用泊松随机计时器在 jmeter 中计算每个请求的思考时间
- javascript - 如何获取数组中每个项目的最后一个元素子元素
- python - 使用具有不同 IP 的 selenium webdriver python 打开 url(使用一些 IP 打开 url,更改 IP 并在 chrome 中再次打开)
- google-apps-script - 如何显示代码的单元格公式,而不是字符串?
- php - 如何通过与第一个收藏相关的记录找到收藏
- java - 将多条数据插入多行到Java中的SQL表中
- c# - 没有 virtual 和 override 的方法覆盖仅返回基类方法
- php - 电子邮件不发送给用户
- jquery - 一个 jQuery 选择器不适用于 safari。怎么了?