我是ReactJS的新手。我需要将Laravel应用程序的前端转换为ReactJS应用程序。在这个应用程序中,我在App.js
文件中创建了一个布局,这个布局在整个应用程序中都是常量。看起来是这样的:
App.js
export default class App extends Component
{
constructor() {
super();
this.state = {
footer: ''
};
}
render()
{
return (
<BrowserRouter>
<Header />
<Switch>
<Route exact path={"/"} component={Index} />
...
</Switch>
<Footer footerData={this.state.footer} />
</BrowserRouter>
);
}
}
Index.jsx
export default class Index extends Component
{
constructor(props) {
super(props);
this.state = {
aboutUs: null
};
}
componentDidMount() {
Axios
.get(`${process.env.REACT_APP_API_URL}home`)
.then((response) => {
const { data } = response.data.response;
this.setState({
aboutUs: data.about_us
});
}).catch((error) => {
console.log(error);
})
}
render()
{
return (
<div className="home">
...
</div>
)
}
}
但是,在Footer
组件中,About us
部分是使用数据库中的数据绘制的,在每个Api请求中都会包含这些数据以及尊重页面上的其他所需数据。
我不想仅仅为了获取本节的数据而创建一个单独的请求。有没有办法将数据从Api传输到App.js
,然后再传输到Footer
组件..?
发布于 2020-01-01 17:55:58
如果要从App.js组件中更新index.jsx组件中的状态,则应将函数从App.js传递给Index.js,后者更新App.js组件中的状态。为此,我添加了方法updateAboutUs
。
App.js
export default class App extends Component
{
constructor() {
super();
this.state = {
footer: ''
aboutUs: null,
};
this.updateAboutUs = this.updateAboutUs.bind(this);
}
function updateAboutUs(data) {
this.setState({aboutUs: data});
}
render()
{
return (
<BrowserRouter>
<Header />
<Switch>
<Route exact path={"/"} render={(props) => <Index {...props} updateAboutUs={this.updateAboutUs} />} />
...
</Switch>
<Footer footerData={this.state.footer} />
</BrowserRouter>
);
}
}
Index.jsx
export default class Index extends Component
{
constructor(props) {
super(props);
this.state = {
aboutUs: null
};
}
componentDidMount() {
Axios
.get(`${process.env.REACT_APP_API_URL}home`)
.then((response) => {
const { data } = response.data.response;
//this.setState({
// aboutUs: data.about_us
//});
this.props.updateAboutUs(data.about_us);
}).catch((error) => {
console.log(error);
})
}
render()
{
return (
<div className="home">
...
</div>
)
}
}
希望这能帮上忙。
https://stackoverflow.com/questions/59554192
复制相似问题