React Native setState 不重新渲染

时间:2020-12-31 15:06:35

标签: react-native react-native-android

我正在为大学项目制作游戏。我不明白为什么当我使用 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>

2 个答案:

答案 0 :(得分:1)

您正在将状态设置为函数。 setState 回调接受值本身,而不是返回值的回调。你需要改变:

setStatus(() => statusAux);

致:

setStatus(statusAux);

除此之外……您正在改变原始对象,您需要为 React 创建一个新对象以检测更改。您可以使用扩展运算符 像这样:

let statusAux = {...status};

答案 1 :(得分:0)

尝试这样做,不需要使用“()=>”

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);
        
    }