如何将从子孙组件中获取的消息提供给祖父母组件?
我已经看到了in the React docs中描述的提升状态的示例。但是该示例以及与此相关的许多其他示例都有用户与按钮进行交互的用例。
还有一些来源(source 1)显示可以使用Redux。但是对于我的应用程序来说,这感觉有些过头了。
似乎应该将状态移到最高部分,在本例中为祖父母。
例如,使用以下代码:
class Page extends React.Component {
state = {
error: false;
}
public render() {
const { error } = this.state;
return(
{!error && <Child><p>All is well!</p></Child>}
{error &&
<p>This message should show only when grandchild has a problem and show the message from the GrandChild.</p>
}
)
}
}
class Child extends React.Component {
render() {
return (
<GrandChild><p>Here in my app the result of the grandchild is used via context. But unrelated to this question.</p></GrandChild>
)
}
}
class GrandChild extends React.Component {
public componentDidMount() {
this.fetchClasses('http://myurl.com/api/v1/')
}
public fetchClasses(url) {
fetch(url)
.then(res => {
if(res.status === 401) {
// error message that should be passed to my grandparent
this.setState({error: true, loading: false});
}
return res.json();
}).then(resJson => {
// phew! everything went well, nothing to worry about
this.setState({error: false, loading: false})
}).catch({
// also a more generic error message my grandparent should know about
this.setState({error: true, loading: false})
});
}
render() {
const { error, loading } = this.state;
return (
{loading && <p>Please tell my grandparent to wait.</p>}
{error && <p>Please tell my grandparent something' wrong.</p>}
{!error && !loading && <p>My grand parent does not have to know</p>}
)
}
}
将状态和信息向上传递的解决方案是什么?