reactjs - React Native 从 API 获取父与子的数据
问题描述
我是 React Native 的新手,所以想知道关于以下场景的最佳实践。
我的通知屏幕组件包含嵌套的子组件,如下所示:
NotificationsScreen ReadSection ReadList UnreadSection UnreadList
我应该在哪里处理状态并进行 API 调用?
选项1:
在 ScreenComponent 构造函数和 componentDidMount 中:
this.state = {
loading: true,
notifications: [],
error: ''
componentDidMount() {
const headers = {
Authorization: this.props.jwt
};
axios({
method: 'GET',
url: 'http://localhost:3000/notifications',
headers: headers,
}).then((response) => {
this.setState({
notifications: response.data.data,
loading: false
然后我必须将通知状态对象作为道具传递给子组件 ReadList 和 UnreadList,分别过滤掉已读和未读通知并呈现列表。
选项 2:
对子 List 组件中的 API 进行 API 调用:
constructor(props) {
super(props);
this.state = {
loading: true,
read_notifications: [],
error: ''
};
}
componentDidMount() {
const headers = {
Authorization: this.props.jwt
};
axios({
method: 'GET',
url: 'http://localhost:3000/notifications?status=read',
headers: headers,
}).then((response) => {
this.setState({
notifications: response.data.data,
loading: false
在这种情况下,我将有 2 个 API 调用,每个组件调用一个,这并不理想,而且我不知道如何在数据加载时处理父控制器的加载渲染,因为子仅渲染列表,而不是整个屏幕。
所以我猜选项 1 会更可取,但这意味着将整个通知数组传递给子组件,并对每个子组件中潜在的数百条记录进行过滤。
有没有我没有想到的第三种选择?提前致谢。顺便说一句,我还没有使用 Redux,所以现在想避免任何涉及外部通量库的解决方案。
解决方案
有两种类型的组件作为最佳实践。有状态和纯组件。有些人也称它们为容器和展示组件。状态始终应由有状态/容器组件处理。展示组件不处理状态,只访问父组件状态。
推荐阅读
- c# - 如何在 C# MVC 中缓存方法返回值
- mysql - mysql LAST_DAY() 只读取1个子查询结果,如何处理所有结果?使用连接?
- python - 多次匹配括号内的文本
- python - Tinymce - name='text' 的无效表单控件不可聚焦
- python - 从文本文件中读取并存储在数组中
- ruby-on-rails - Rails:如果模型属性为真,则在视图中执行以下操作
- reactjs - 为什么useState在获取数据后不起作用
- java - 使用 Apache poi 断开指向外部工作簿的链接
- c# - 如何根据命令行中的列表框选择执行单独的脚本?
- reactjs - 我应该在这个简单的 ReactJS 页面中使用 State 还是 Props?