【发布时间】:2018-11-29 23:42:03
【问题描述】:
首先,我尝试检查用户的 ID 是否与 DB 中的 ID 匹配。如果是这样,那么为hasApplied 和toggle 设置一个新状态,但我收到以下警告Cannot update during an existing state transition (such as within 'render' or another component)...
我什至尝试调用一个在渲染之外的函数并且说同样的事情。但是,如果我通过按钮组件的onPress={} 方法在渲染之外调用该函数,那么一切都很好。但在这种情况下,我需要在用户访问页面时首先检查这一点,如果 hasApplied 返回 false 然后使用按钮
render() {
let { hasApplied } = this.state;
let { toggle } = this.state;
let matchUserId = [];
const textValue = toggle ? 'APPLIED' : 'APPLY NOW';
const buttonBg = toggle ? '#848d95' : '#34ed1c';
const buttonState = toggle ? 'false' : 'true';
const { navigation } = this.props;
const { goBack } = this.props.navigation;
const { jobBusiness, locationBusiness } = this.props.navigation.state.params;
let { user, location, job, data, business } = this.props.navigation.state.params;
// Check the available applied ids and concatenate objects in Array
// Check if user_id match any of appliedUserId
if (!hasApplied) {
job.applied.map(o => {
matchUserId.push(o.user_id);
});
const resultUserId = [].concat.apply([], matchUserId);
hasApplied = resultUserId.includes(this.props.user_id)
// this.onButtonPress()
this.setState({hasApplied: true, toggle: true})
}
谁能解决这个问题?
谢谢
【问题讨论】:
-
没有理由不能在另一个组件方法中使用该代码。 React 阻止了从 render 方法调用 setState,因为它很有可能出现无限循环。看到这个问题:stackoverflow.com/questions/48226268/…
标签: javascript reactjs react-native