我有这个功能。
async function search() {
try {
const response = await places.nearbysearch({
location: text, // LatLon delimited by ,
radius: distance, // Radius cannot be used if rankBy set to DISTANCE
type: ['cafe','bakery','meal_delivery','meal_takeaway','restaurant'], // Undefined type will return all types
// rankby: "distance" // See google docs for different possible values
});
const { status, results, next_page_token, html_attributions } = response;
var index = Math.floor(Math.random() * response.results.length);
console.log(response.results[index].name);
restName = response.results[index].name;
console.log(restName);
} catch (error) {
console.log(error);
}
}
它是在... export default function App() {}
我在视图中做了一个文本内容,就像这样。
return (
<View style={styles.container}>
<View style={{minWidth: '100%', minHeight: '100%', backgroundColor: '#f0fbff', alignFit:'stretch', marginTop: 0, alignItems:'center', justifyContent:'space-evenly'}}>
<Card style={{padding: 5, margin: 1}}>
<Text style={{ fontWeight: 'bold', fontSize: 25, }}>{restName}{"\n"}</Text>
即使restName更新了(我做了一个按钮,按下后会运行search()函数),文本也没有更新,我如何用这个实现set state或者刷新变量。当我console.log restName的时候,它显示的是正确的东西,所以我知道变量已经更新了,只是文本没有更新。
简而言之,实际的变量发生了变化,但它并没有显示任何不同的内容。
更新 我试着用setstate,但它仍然没有更新,下面看看这个功能。
var restName = "";
async function search() {
try {
const response = await places.nearbysearch({
location: text, // LatLon delimited by ,
radius: distance, // Radius cannot be used if rankBy set to DISTANCE
type: ['cafe','bakery','meal_delivery','meal_takeaway','restaurant'], // Undefined type will return all types
// rankby: "distance" // See google docs for different possible values
});
const { status, results, next_page_token, html_attributions } = response;
var index = Math.floor(Math.random() * response.results.length);
console.log(response.results[index].name);
this.setState({ restName : response.results[index].name })
console.log(restName);
} catch (error) {
console.log(error);
}
}
要想更新状态,你不能只是重新指定
restName = response.results[index].name
但要打电话 setState
this.setState({ restName : response.results[index].name })