两个接口,第一个接口有得数据,如果第二个接口也有就在第二个接口数据得基础上加上disable:false。两个个接口得类型为[ { "id": 1, "userId": 22027, "mobile": "17688838060", }, { "id": 2, "userId": 22028, "mobile": "15272414126", } ];用react hooks写个例子
时间: 2023-07-19 08:47:30 浏览: 35
好的,以下是一个使用 React Hooks 的例子,实现了上述需求:
```jsx
import { useState, useEffect } from 'react';
function App() {
const [data1, setData1] = useState([]);
const [data2, setData2] = useState([]);
useEffect(() => {
fetch('https://api.example.com/data1')
.then(response => response.json())
.then(data => setData1(data));
}, []);
useEffect(() => {
fetch('https://api.example.com/data2')
.then(response => response.json())
.then(data => {
setData2(data.map(item => {
const match = data1.find(d => d.userId === item.userId);
if (match) {
return { ...item, disable: false };
} else {
return item;
}
}));
});
}, [data1]);
return (
<div>
<h1>Data 1:</h1>
<ul>
{data1.map(item => (
<li key={item.id}>{item.mobile}</li>
))}
</ul>
<h1>Data 2:</h1>
<ul>
{data2.map(item => (
<li key={item.id}>{item.mobile} {item.disable ? '(disabled)' : ''}</li>
))}
</ul>
</div>
);
}
export default App;
```
这个例子中,我们使用了两个 `useState` 来保存两个接口的数据。在两个 `useEffect` 中,我们使用 `fetch` 来获取接口数据,并且使用 `setData1` 和 `setData2` 更新状态。在第二个 `useEffect` 中,我们对第二个接口的数据进行了处理,根据第一个接口的数据来确定是否需要加上 `disable: false`。最后,在渲染时,我们分别展示了两个接口的数据。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)