我正在尝试在用户给出自己的评分后更新平均评分。我设法更新了对象,但不确定如何使它重新呈现组件,因此将显示新的平均值。我这部分的代码:
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;
});
})
}
谢谢!
答案 0 :(得分:1)
这样您就可以更新状态(挂钩)
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
});
})
}
}
答案 1 :(得分:1)
要重新渲染组件,您应该更改state或props变量。
在您的情况下,当您使用doRate
更新时,要在props中进行更改,应在父组件中重新获取数据。
或者,您可以更改状态变量:
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);
});
})
}