[英]fetch data from a component and render it in another component
有什么线索为什么下面的代码不起作用? 这只是一个简单的ajax调用,然后尝试在另一个组件中进行渲染。 我不知道错误在哪里。
var Names = React.createClass({
getInitialState: function () {
const self = this;
const names = fetch('https://api.myjson.com/bins/ksgah')
.then(function(response) {
return response.json()
})
.then(function(response) {
self.setState({'names':response.name})
})
return {names: names};
},
render() {
return (
<Hello name={this.state.names}/>
)
}
})
var Hello = React.createClass({
render: function() {
return(
<ul>
{
this.props.names.map(name => {
return <li>{name}</li>
})
}
</ul>
)
}
})
ReactDOM.render( <Names/> , document.getElementById('container'));
将引号改为{}
// from:
<Hello name="this.state.names"/>
//to:
<Hello name={this.state.names}/>
设置状态也错误使用:相反,
首先,在getInitialState
中的names
常量中获得Promise
,并将状态{names:Promise}返回到组件中。 因此它没有map
方法并且失败了。
因此,您应该返回一个没有任何异步操作的有效initialState,例如: getInitialState: function() { return { names: [] }; }
getInitialState: function() { return { names: [] }; }
。
例如,然后在componentDidMount
上进行异步调用和更新状态。
检查一下: 固定jsfiddle
<Hello name={this.state.names}/>
您正在传递属性name
而组件需要names
。
另外, names
在开始时应该为空数组,而不是对Promise的引用:
getInitialState: function () {
const self = this;
fetch('https://api.myjson.com/bins/ksgah')
.then(function(response) {
return response.json()
})
.then(function(response) {
self.setState({'names':response.name})
})
return {names: []};
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.