我正在尝试制作一个漂亮的ApiWrapper组件来填充各种子组件中的数据.从我读过的所有内容来看,这应该有效:https://jsfiddle.net/vinniejames/m1mesp6z/1/
class ApiWrapper extends React.Component {
constructor(props) {
super(props);
this.state = {
response: {
"title": 'nothing fetched yet'
}
};
}
componentDidMount() {
this._makeApiCall(this.props.endpoint);
}
_makeApiCall(endpoint) {
fetch(endpoint).then(function(response) {
this.setState({
response: response
});
}.bind(this))
}
render() {
return <Child data = {
this.state.response
}
/>;
}
}
class Child extends React.Component {
constructor(props) {
super(props);
this.state = {
data: props.data
};
}
render() {
console.log(this.state.data, 'new data');
return ( < span > {
this.state.data.title
} < /span>); …Run Code Online (Sandbox Code Playgroud) 我知道我可以props在渲染组件时通过.我也知道这个getInitialState方法.但问题是,getInitialState并不是很有帮助,因为我的组件不知道它的初始状态.我做.所以我想在渲染时传递它.
像这样的东西(伪代码):
React.render(<Component initialState={...} />);
Run Code Online (Sandbox Code Playgroud)
我知道我可以使用a prop作为初始状态,但这闻起来像一个反模式.
我该怎么办?
编辑清晰度
想象一下,我有一个CommentList组件.到我第一次渲染它时,初始状态对应于我数据库中当前注释的快照.当用户包含评论时,此列表将会更改,这就是为什么它应该是a state而不是props.现在,为了呈现注释的初始快照,我应该将它传递给CommentsList组件,因为它无法知道它.我的困惑是,我看到传递这些信息的唯一方法是通过一个props似乎是反模式的方式.
当设置组件的初始状态时,使用通过props传入的数据,我应该创建一个新对象,做类似......
getInitialState: function () {
return {
fieldData: JSON.parse(JSON.stringify(this.props.data))
};
}
Run Code Online (Sandbox Code Playgroud)
或者只是做...
getInitialState: function () {
return {
fieldData: this.props.data
};
}
Run Code Online (Sandbox Code Playgroud) 我是React的新手.我坚持这个,真的很感激一些帮助!
父组件将数组传递给此子组件.当我在console.log(this.props.repairs)时,它向我显示了一个4的数组.每当传入修复数组时,我都会尝试更新this.state.sortedDataList.控制台.log(this.state)仍然是将sortedDataList显示为空数组.
我究竟做错了什么?非常感谢,感谢任何帮助.
class Repairs extends React.Component {
constructor(props) {
super(props);
this.state = {
sortedDataList: []
};
}
componentWillReceiveProps(nextProps) {
if(this.props != nextProps) {
this.setState({
sortedDataList: this.props.repairs
});
}
}
render() {
console.log(this.props);
console.log(this.state);
return (
<div></div>
);
}
}
Run Code Online (Sandbox Code Playgroud) 假设我的父组件有两个子组件:
Parent
| Child1
| Child2
Run Code Online (Sandbox Code Playgroud)
我从Child2获得了一个输入,并将它传递给Parent组件(直到现在,我知道该怎么做).但是我需要将该输入传递给Child1以更新它的状态.
我怎样才能做到这一点?