reactjs - ReactJS:从路由中获取数据并通过父组件将其传递给组件
问题描述
我是 ReactJS 的新手。我需要将 Laravel 应用程序的前端转换为 ReactJS 应用程序。在这个应用程序中,我在App.js
文件中创建了一个布局,该布局在整个应用程序中都是不变的。看起来像这样:
应用程序.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>
);
}
}
索引.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
组件..?
解决方案
如果您想从 index.jsx 组件更新 App.js 组件中的状态,您应该将函数从 App.js 传递给 Index.js,它会更新 App.js 组件中的状态。我updateAboutUs
为此添加了方法。
应用程序.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>
);
}
}
索引.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>
)
}
}
希望这会有所帮助。
推荐阅读
- excel - Excel:如何创建带有下拉日期选择的周历?
- javascript - 寻找更好的方式在 JavaScript 中创建路径以实现最大捕获
- java - 为什么活动和片段之间的通信需要 onAttach()?
- php - PHP mysql获取行但结果为空?
- javascript - 获取设备(手机、笔记本电脑、平板电脑等)名称,使用原生 javascript 输入
- python - 为所有用户将 Python 代码添加到 Smartsheets
- bash - 带有过滤器的 Ping 脚本
- php - DESCRIBE 表时出现 PDO 异常
- jquery - 如何在下拉列表中设置默认值
- python - PyInstaller - PyInstaller 不编译我导入的脚本