Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/21.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
Json 设置状态问题_Json_Reactjs - Fatal编程技术网

Json 设置状态问题

Json 设置状态问题,json,reactjs,Json,Reactjs,我似乎在努力解决一个简单的关于设置状态的问题。我正在学习React,所以我通过几个步骤完成了这项工作。最初,我设置我的组件,以便它们使用props(例如,this.propsoverview[0].ProfileImg)设置字段,该props是从概览窗格中传递的状态,最初是使用componentWillMount中的this.SetState调用设置的,其中数据是从静态文件中提取的 接下来,我添加了一个函数,以更动态的方式提取数据(即getPatient函数)。我从componentWillMo

我似乎在努力解决一个简单的关于设置状态的问题。我正在学习React,所以我通过几个步骤完成了这项工作。最初,我设置我的组件,以便它们使用props(例如,this.propsoverview[0].ProfileImg)设置字段,该props是从概览窗格中传递的状态,最初是使用componentWillMount中的this.SetState调用设置的,其中数据是从静态文件中提取的

接下来,我添加了一个函数,以更动态的方式提取数据(即getPatient函数)。我从componentWillMount调用这个函数,并且我能够通过console.log将JSON作为字符串输出(使用JSON.stringify)。所以我知道JSON正在被返回

我正在努力使用getPatient调用返回的JSON在componnetWillMount中设置状态。我得到错误未捕获(在prmise中)类型错误:无法读取代码第4行未定义的属性“setState”(即此.setState…)

下面是我的代码

componentWillMount() {
     getPatient().then(function(result) {
     //console.log(JSON.stringify(result));
     this.setState({PATIENT: result})
})


function getPatient() {
     const urlGetPatient = 'url_that_gets_patient_here';
     return fetch(urlGetPatient).then(function(response) {
       return response.json();
     }).then(function(json) {
       return json;
     }); 
 }

 render() {
     return (
       <App>
        …
       <OverviewPane overview={this.state.PATIENT} />
        …
       </App>
      }

class OverviewPane extends React.Component { 
     constructor(props) {
        super(props);
        autoBind(this);
     }

     render () {
        return (
         <table>
           <tbody>
             <tr>
              <td><Image src={this.props.overview[0].ProfileImg}/></td>
             </tr>
           </tbody>
          </table>
          );
        }
    }
componentWillMount(){
getPatient().then(函数(结果){
//log(JSON.stringify(result));
this.setState({PATIENT:result})
})
函数getPatient(){
const urlGetPatient='url\u该患者在这里得到患者';
返回fetch(urlGetPatient)。然后返回(函数(响应){
返回response.json();
}).then(函数(json){
返回json;
}); 
}
render(){
返回(
…
…
}
类概览窗格扩展了React.Component{
建造师(道具){
超级(道具);
自动绑定(本);
}
渲染(){
返回(
);
}
}

非常感谢您的帮助。

您的代码中的
在承诺范围内,您需要绑定
,以获得反应
范围

getPatient().then(function(result) {
    //console.log(JSON.stringify(result));
    this.setState({PATIENT: result})
}.bind(this))

您得到的是
无法调用未定义的setState
,因为您使用的是常规
函数
作为回调函数,而不是箭头函数(
()=>{}
)。使用常规函数时,
参数(上下文)设置为调用函数,而不是您可能认为的(所谓的词法
this

更改
。然后将
回调更改为箭头函数,您应该可以:

componentWillMount() {
  getPatient().then((result) => {
    this.setState({PATIENT: result});
  })
}
可能重复。请检查第二个答案。