如果 else 语句不会自动运行函数,则本机反应



试图在 react native 中的 if else 语句上运行一个函数,但是如果我像这样直接调用它.removeAlert(( 由于调用 setState,我会得到无限循环崩溃。我读到你应该在一个函数中调用它,它在 onPress 函数中工作正常,但对我来说,它不能在函数之外工作。

class Settingscontainer extends Component {
constructor() {
super();
this.removeAlert = this.removeAlert.bind(this);
}
removeAlert = () => {
console.log("please work");
// this.setState({ successAlert: false });
};
render() {
this.props.isFocused
? console.log("Focused") // console.log working
: () => {                // not working
this.removeAlert();
};
return(<View>code...</View>
)  
}}

你所做的相当于这个:

function callRemoveAlert() {
this.removeAlert();
}
this.props.isFocused
? console.log("Focused")
: callRemoveAlert

定义一个函数来调用this.removeAlert(),但从不调用该函数。要使代码正常工作,您需要执行以下操作:

this.props.isFocused
? console.log("Focused")
: this.removeAlert()

但是由于在removeAlert中,您打算修改状态,因此我认为您不应该这样做。默认情况下,React 组件,随着 props 和状态的每次更改,都会调用render。通过您的实现,render将触发setState,状态更改将触发render,从而导致状态更新和渲染的无限循环。更好的方法是使用componentDidUpdate

componentDidUpdate(prevProps) {
if (this.props.isFocused !== prevProps.isFocused) {
(this.props.isFocused) ?
? console.log("Focused")
: this.removeAlert();
}
}
render() {
return(<View>code...</View>
)  
}}

相关内容

最新更新