对象更新后如何重新渲染组件?

How to rerender component after object update?

我正在尝试在用户给出自己的评分后更新平均评分。我设法更新了对象,但不确定如何让它重新渲染组件,所以新的平均值会出现。我这部分的代码:

const pizza = props.route?.params?.pizza ?? null;

const rateClicked = () => {
    doRate(pizza.id, highlight, token)
    .then( resp => {
        Alert.alert("Rating", resp.message);
        doGetDetails(pizza.id, token).then( resp => {
            pizza.avg_rating = resp.avg_rating;
        });
    })
}

谢谢!

这样你就可以更新状态(Hooks)

export default function Details(props) {
 
  const [pizzaData, setPizzaData] = useState(props.pizza); <-- "props.pizza" is default -->

  const rateClicked = () => {
    doRate(pizza.id, highlight, token)
    .then( resp => {
        Alert.alert("Rating", resp.message);
        doGetDetails(pizza.id, token).then( resp => {
            const pizzaData = {...pizzaData};
            pizzaData.avg_rating = resp.avg_rating;
            setPizzaData(pizzaData); // reset state here to rerender 
        });
    })
  }
}

为了使组件 re-render,您应该更改状态或道具变量。

在您的情况下,当您使用 doRate 更新时,要在道具数据 re-fetch 中更改它应该在父组件中完成。
或者你可以改变一个状态变量:

const pizza = props.route?.params?.pizza ?? null;

const rateClicked = () => {
    doRate(pizza.id, highlight, token)
    .then( resp => {
        Alert.alert("Rating", resp.message);
        doGetDetails(pizza.id, token).then( resp => {
            this.setState(avg_rating: resp.avg_rating);
        });
    })
}