gpt4 book ai didi

javascript - 是否可以使用 react.js 将 promise 数据值分配给外部变量

转载 作者:行者123 更新时间:2023-11-30 06:50:53 24 4
gpt4 key购买 nike

是否可以在 react 中将 promise 数据值分配给外部变量?

我想做这样的事情:

export default class LocationSearchInput extends Component {
constructor(props) {
super(props);
this.state = {address: ''}
}

handleChange = (address) => {
this.setState({ address });
};

handleSelect = (address) => {
geocodeByAddress(address)
.then(results => getLatLng(results[0]))
.then(latLng => console.log(latLng))
.catch(error => console.error('Error', error));
};
render() { ........

在这个例子中,我得到了我想要的:latLng,但我不能在外面使用它。它在 SearchBox.js 文件中,我想将它包含在另一个 Map.js 文件中。我是新手,非常感谢!

最佳答案

处理这种情况的最佳方法是在需要使用 latLng 的 topMost 父级中设置一个函数,然后调用 API 并保存 LatLng状态并将此值作为 Prop 传递给 LocationSearchInput 和其他需要它的组件

class Parent extends React.Component {
handleGeocodeByAddress(address) {
geocodeByAddress(address)
.then(results => getLatLng(results[0]))
.then(latLng => this.setState({ latLng }))
.catch(error => console.error('Error', error));
}
render() {
return <Child layLng={this.state.latLng} handleGeocodeByAddress={handleGeocodeByAddress} />
}
}

然后调用子函数的父函数

export default class LocationSearchInput extends Component {

constructor(props) {
super(props);
this.state = {address: ''}
}

handleChange = (address) => {
this.setState({ address });
};

handleSelect = (address) => {
this.props.handleGeocodeByAddress(address);
};
render() { ........

关于javascript - 是否可以使用 react.js 将 promise 数据值分配给外部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50290964/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com