我有以下组件。如果满足条件,我想运行一个动作(this.props.selectCharacter)。但是,这会导致无限循环当前最大调用堆栈超过
组件/ board.js
componentDidUpdate() {
this.props.characters.map((character) => {
// if the character is located correctly
if(character.found === true) {
// hide the overlay
document.getElementById(character.id).style.display = 'none';
// go to next character
var nextCharacter = {
id: '_x30_2-A-Kenard',
name: 'Kenard',
'avatar': 'img/2.jpg',
found: false
};
this.props.selectCharacter(nextCharacter);
}
});
}
操作/ index.js
export function selectCharacter(character) {
// Action creator; needs to return an action (an object with a type property)
return {
type: 'CHARACTER_ACTIVATED',
payload: character
};
}
减速器/ reducer_active_character.js
export default function(state = { id: '_x30_1-A-RussellStringerBell', name: 'Stringer Bell', avatar: 'img/1.jpg', found: false }, action) {
switch(action.type) {
case 'CHARACTER_ACTIVATED':
return action.payload;
}
return state;
}
答案 0 :(得分:0)
您的问题是character.found === true
中的一个会更新字符,从而导致组件更新。 “
console.log(characters)
,发现有一个character.found === true
将componentDidUpdate更改为:
const newCharacters = character.map(c => {
return c.found ? { // new character } : c;
});
this.props.selectCharacters(newCharacters);