Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/398.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在执行render方法之前,使用承诺为状态赋值_Javascript_Reactjs_Axios_Es6 Promise_Es6 Class - Fatal编程技术网

Javascript 如何在执行render方法之前,使用承诺为状态赋值

Javascript 如何在执行render方法之前,使用承诺为状态赋值,javascript,reactjs,axios,es6-promise,es6-class,Javascript,Reactjs,Axios,Es6 Promise,Es6 Class,编辑: (使用chrome)我将JSON分配给状态,而不是进行api调用。不过,我正在尝试对api调用执行相同的操作 在运行render()方法之前,如何将值分配给state属性locoData locoData从不被分配,并且console.log(相应的数据)在render方法之后执行。我是一个新的反应者,刚刚赶上JavaScript中更新的特性,比如promises,这让我很困惑。我正在执行这个代码 如果我将JSON分配给状态,而不是尝试使用axios.get方法,那么它可以正常工作。JS

编辑:

(使用chrome)我将JSON分配给状态,而不是进行api调用。不过,我正在尝试对api调用执行相同的操作

在运行
render()
方法之前,如何将值分配给state属性
locoData

locoData
从不被分配,并且
console.log(相应的数据)在render方法之后执行。我是一个新的反应者,刚刚赶上JavaScript中更新的特性,比如promises,这让我很困惑。我正在执行这个代码

如果我将JSON分配给状态,而不是尝试使用
axios.get
方法,那么它可以正常工作。JSON响应位于底部

我取下了bing地图的钥匙

  const LocationData = (props) => (
    <div>
      {props.location => <Location key={location.traceId} {...location}/>}
    </div>
)

class Location extends React.Component {    
    state = { locoData: {} },   
    const a = axios.get("https://dev.virtualearth.net/REST/v1/Locations?CountryRegion=US&adminDistrict=WA&locality=Somewhere&postalCode=98001&addressLine=100%20Main%20St.&key=bingMapKey").then(resp => { 
      console.log(resp.data);
      this.setState({ locoData: resp.data });  
    });

  render() {     
    resources = this.state.locoData.resourceSets[0].resources.map(function(resource){      
      return <div className="resource" key={resource.name} {...resource}></div>;
    });
    return (
        <div>
          <img src={location.brandLogoUri} />
        <div>
          <div>{resources.name}</div>
          <div>{resources[0].props.point.coordinates[0]} {resources[0].props.point.coordinates[1]}</div>
        </div>
        </div>
    );
  }
}

class App extends React.Component {
  state = {
    location: [],
  };
  displayLocation = (locationData) => {
    this.setState(prevState => ({
        location: [...prevState.location, locationData],
    }));
  };
    render() {
    return (
        <div>
          <div>{this.props.title}</div>
        <Location LocationData={this.state.location} />
        </div>
    );
  } 
}

ReactDOM.render(
    <App title="Simple Weather App" />,
  mountNode,
);

{"authenticationResultCode":"ValidCredentials","brandLogoUri":"http:\/\/dev.virtualearth.net\/Branding\/logo_powered_by.png","copyright":"Copyright © 2019 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation.","resourceSets":[{"estimatedTotal":1,"resources":[{"__type":"Location:http:\/\/schemas.microsoft.com\/search\/local\/ws\/rest\/v1","bbox":[47.275809008582883,-122.25881456692279,47.283534443724236,-122.24363249293789],"name":"100 Main St, Algona, WA 98001","point":{"type":"Point","coordinates":[47.279671726153559,-122.25122352993034]},"address":{"addressLine":"100 Main St","adminDistrict":"WA","adminDistrict2":"King County","countryRegion":"United States","formattedAddress":"100 Main St, Algona, WA 98001","locality":"Algona","postalCode":"98001"},"confidence":"High","entityType":"Address","geocodePoints":[{"type":"Point","coordinates":[47.279671726153559,-122.25122352993034],"calculationMethod":"InterpolationOffset","usageTypes":["Display"]},{"type":"Point","coordinates":[47.279653371643015,-122.25128403728938],"calculationMethod":"Interpolation","usageTypes":["Route"]}],"matchCodes":["Good"]}]}],"statusCode":200,"statusDescription":"OK","traceId":"591320e018b0476cbbe71f338ecab555|BN1EAE8F4E|7.7.0.0|Ref A: 3983F574345D41A782020BC15BA6BF08 Ref B: BN3EDGE0210 Ref C: 2019-05-04T04:30:29Z"}
const LocationData=(道具)=>(
{props.location=>}
)
类位置扩展了React.Component{
状态={locoData:{}},
常数a=axios.get(“https://dev.virtualearth.net/REST/v1/Locations?CountryRegion=US&adminDistrict=WA&locality=Somewhere&postalCode=98001&addressLine=100%20Main%20St.&key=bingMapKey)然后(resp=>{
控制台日志(相应数据);
this.setState({locoData:resp.data});
});
render(){
resources=this.state.locoData.resourceSets[0].resources.map(函数(资源){
返回;
});
返回(
{resources.name}
{resources[0].props.point.coordinates[0]}{resources[0].props.point.coordinates[1]}
);
}
}
类应用程序扩展了React.Component{
状态={
地点:[],
};
displayLocation=(locationData)=>{
this.setState(prevState=>({
位置:[…prevState.location,locationData],
}));
};
render(){
返回(
{this.props.title}
);
} 
}
ReactDOM.render(
,
mountNode,
);
{“authenticationResultCode”:“ValidCredentials”,“brandLogoUri”:“http:\/\/dev.virtualearth.net\/Branding\/logo\u powered\u by.png”,“版权”:“版权所有©2019 Microsoft及其供应商。保留所有权利。未经Microsoft Corporation明确书面许可,不得访问此API,也不得以任何方式使用、复制或传输内容和任何结果。”,“资源集”:[{“estimatedTotal”:1,“资源”:[{“\uu类型”:”位置:http:\/\/schemas.microsoft.com\/search\/local\/ws\/rest\/v1,“bbox”:[47.275809008582883,-122.25881456692279,47.2835344443724236,-122.24363249293789],“名称”:“华盛顿州阿尔冈那市100大街98001号”,“点”:{“类型”:“点”,“坐标”:[47.27967172615559,-122.251223529993034],“地址”:“地址线”:“主街道100号”,“行政区”:“华盛顿州”行政区划2:“国王县”、“国家地区”:“美国”、“格式地址”:“华盛顿州阿尔冈那大街100号98001”、“地点”:“阿尔冈那”、“邮政编码”:“98001”;“置信度”:“高”、“实体类型”:“地址”、“地理编码点”:[{“类型”:“点”、“坐标”:[47.27967156559,-122.2512235993034],“计算方法”:“插值偏移量”、“使用类型”:显示“]},{“类型”:“点”,“坐标”:[47.27965371643015,-122.25128403728938],“计算方法”:“插值”,“使用类型”:[“路线”]}],“匹配代码”:[“良好”]}],“状态代码”:200,“状态描述”:“确定”,“跟踪ID”:591320e018b0476cbbe71f338ecab555 | BN1EAE8F4E | 7.7.0.0 |参考A:3983F574345D41A782020BC15BA6BF08参考B:BN3EDGE0210参考C:2019-05-04T04:30:29Z“

我不知道这是否是你问题的正确答案。 React有一个渲染周期,您可以在此处找到:





您可以通过两种方式实现这一点:第一种是使用函数

 componentWillMount(){
    //Here you can set state normally
    }
在安装组件之前运行。 第二种解决方案是使用react钩子的新特性,在本例中,该特性与componentWillMount相同

useEffect(() => {
  return () => {
    //here you can set your state
  }
}, [])

PS:只需使用hook,旧的react循环已被弃用

我不知道它是否是解决您问题的正确答案。 React有一个渲染周期,您可以在此处找到:





您可以通过两种方式实现这一点:第一种是使用函数

 componentWillMount(){
    //Here you can set state normally
    }
在安装组件之前运行。 第二种解决方案是使用react钩子的新特性,在本例中,该特性与componentWillMount相同

useEffect(() => {
  return () => {
    //here you can set your state
  }
}, [])

PS:只需使用hook,旧的react循环已被弃用

您需要使用条件呈现,将一个变量设置为true,如
state={isLoading:true}
一旦从api接收数据,就将其设置为false

类位置扩展React.Component{
状态={locoData:{},isLoading:true,errorMessage:“};
getDataFromApi=()=>{
const t_his=这个;
常数a=axios
.得到(
"https://dev.virtualearth.net/REST/v1/Locations?CountryRegion=US&adminDistrict=WA&locality=Somewhere&postalCode=98001&addressLine=100%20Main%20St.&key=bingMapKey"
)
。然后(resp=>{
控制台日志(相应数据);
t_his.setState({locoData:resp.data,isLoading:false});
})
.catch(函数(错误){
他的状态({
errorMessage:“出现错误,状态:”+Error.response.status,
孤岛加载:false
});
});
};
componentDidMount=()=>{
此参数为.getDataFromApi();
};
render(){
常数资源数据=
(this.state.locoData&&
this.state.locoData.resourceSets&&
this.state.locoData.resourceSets[0].resources)||
[];
const resources=resourcesData.map(函数(资源){
返回;
});
const name=(资源和资源[0]&&resources[0].props.name)| |“”;
常数坐标=
(资源和资源[0]&&resources[0]。道具。点。坐标[0])||
"";
常量坐标1=
(资源和资源[0]&资源[0]。道具。点。坐标[1])||
"";
返回(
{this.state.isLoading(
)