React:在渲染之前执行一些检查
React: Execute some check before render
有没有实现这个想法的方法:
我想在渲染前做一些检查。如果检查为真则渲染。但是如果检查是假的,那么首先我需要做 setState
,并且只有在渲染之后。
谢谢。
我认为 componentWillMount()
确实是您所追求的,但将它放在 constructor()
中可能是一个更好的地方。
class MyComponent extends React.Component {
constructor(props) {
super(props);
if (theCheck() === false) {
this.state = {
// ...
}
}
}
}
先尝试渲染它,然后使用 componentDidMount()
检查并在已经渲染后更改状态。别担心,它来得太快了,你的眼睛看不到它。代码将如下所示:
class MyApp extends React.Component {
componentDidMount() {
if (CHECK HERE) {
this.setState({state : stateValue})
}
}
}
有没有实现这个想法的方法:
我想在渲染前做一些检查。如果检查为真则渲染。但是如果检查是假的,那么首先我需要做 setState
,并且只有在渲染之后。
谢谢。
我认为 componentWillMount()
确实是您所追求的,但将它放在 constructor()
中可能是一个更好的地方。
class MyComponent extends React.Component {
constructor(props) {
super(props);
if (theCheck() === false) {
this.state = {
// ...
}
}
}
}
先尝试渲染它,然后使用 componentDidMount()
检查并在已经渲染后更改状态。别担心,它来得太快了,你的眼睛看不到它。代码将如下所示:
class MyApp extends React.Component {
componentDidMount() {
if (CHECK HERE) {
this.setState({state : stateValue})
}
}
}