react-native - React Native setState 不重新渲染
问题描述
我正在为大学项目制作游戏。我无法弄清楚为什么当我使用 setState() 作为状态时它没有重新渲染屏幕,但是当我使用傻瓜时它确实如此。如果我使用 console.log(status) 在 setStatus 之后被更改。
const [status, setStatus] = React.useState({ astrounauts: 0, research: 0, money: 0, publicity: 0 });
const [fool, setFool] = React.useState(false);
const acceptCard = (index) => {
let statusAux = status;
statusAux.astrounauts += cards[index].acceptCardStatus.astrounauts;
statusAux.research += cards[index].acceptCardStatus.research;
statusAux.money += cards[index].acceptCardStatus.money;
statusAux.publicity += cards[index].acceptCardStatus.publicity;
//no re-render... =C
setStatus(() => statusAux);
//it does trigger re-render, not working without that.. this is dumb
setFool(() => !fool);
}
...
<View style={styles.cardsOptions}>
<Swiper
cards={cards}
renderCard={(card =>
<Card card={card} />
)}
onSwipedRight={(cardIndex) => acceptCard(cardIndex)}
onSwipedLeft={(cardIndex) => rejectCard(cardIndex)}
// onSwiped={(cardIndex) => { console.log(cardIndex) }}
onSwipedAll={() => { console.log('onSwipedAll') }}
disableBottomSwipe={true}
disableTopSwipe={true}
outputRotationRange={["-10deg", "0deg", "10deg"]}
cardIndex={0}
backgroundColor={'#18191A'}
stackSize={100}
>
</Swiper>
</View>
解决方案
您正在将状态设置为函数。setState 回调接受值本身,而不是返回值的回调。你需要改变:
setStatus(() => statusAux);
到:
setStatus(statusAux);
除此之外......您正在改变原始对象,您需要为 React 创建一个新对象以检测更改。您可以像这样使用扩展运算符:
let statusAux = {...status};