Reactjs 在React中导出异步函数的结果
我正在使用.NET Core构建React应用程序,并将一些常量值放入appsettings.json文件nothing sensitive中,并将这些值作为API控制器公开。我的想法是将API调用放在一个.js文件中,并将这些值作为常量公开,以便它们在所有其他.js文件中都可用 我有以下资料:Reactjs 在React中导出异步函数的结果,reactjs,Reactjs,我正在使用.NET Core构建React应用程序,并将一些常量值放入appsettings.json文件nothing sensitive中,并将这些值作为API控制器公开。我的想法是将API调用放在一个.js文件中,并将这些值作为常量公开,以便它们在所有其他.js文件中都可用 我有以下资料: var y = "foo"; function successCallback(resp) { y = resp; console.log(y); //shows expected v
var y = "foo";
function successCallback(resp) {
y = resp;
console.log(y); //shows expected value
}
async function readConfig() {
fetch('api/ClientConfiguration')
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error('error...')
}
})
.then(responseJson => {
successCallback(responseJson.apiUrl);
});
}
readConfig();
console.log(y); //shows "foo"
export const clientConfig = {
apiUrl: y
};
我知道fetch的异步特性使得constclientconfig中的属性始终具有foo值。是否有一种方法可以使用此方法或其他方法导出我想要的值?谢谢。这是一种特殊情况
以后可以分配它:
function successCallback(resp) {
clientConfig.apiUrl = resp;
}
...
export const clientConfig = {
apiUrl: null
};
不应该这样做;当模块导入在其他模块中使用时,结果可能不存在,并且无法跟踪它何时出现
正确的方法是出口承诺:
export const clientConfig = fetch('api/ClientConfiguration')
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error('error...')
}
})
.then(responseJson => {
return { apiUrl: responseJson.apiUrl };
});
看起来没有一种简单或优雅的方法可以做到这一点,事情的异步本质也是如此。我要做的是制作一个执行抓取的组件,然后让该组件在完成后将值传递给子组件 下面是一个粗略编写的示例。你可以让它更灵活地使用,这将允许你更无缝地在树下传递值,或者允许你在这里用任何其他组件替换应用程序。无论哪种方式,都有很多方法可以实现这一点
class ClientConfigProvider extends React.Component {
state = {
response: null,
error: null,
}
componentDidMount() {
fetch("api/ClientConfiguration")
.then((response) => {
if (response.ok) {
return response.json()
} else {
this.setState({ error: "oops" })
}
})
.then((response) => {
this.setState({ response })
})
}
render() {
if (error) {
return <div>Error while fetching config: {this.state.error}</div>
}
if (response) {
return <App apiUrl={this.state.response.apiUrl} />
}
return <div>Loading...</div>
}
}
不客气。是的,这本来应该是一个承诺。您可以在父组件中打开一个承诺,将其作为对象道具传递给子组件,请参阅另一个答案以获得一些启示。