react数组维护多个loading
时间: 2023-08-18 13:06:20 浏览: 58
可以使用一个布尔类型的 state 数组来维护多个 loading 状态,例如:
```
const [loadingList, setLoadingList] = useState([false, false, false]);
const handleLoading = (index) => {
setLoadingList(prevState => {
const newState = [...prevState];
newState[index] = true;
return newState;
});
};
const handleLoaded = (index) => {
setLoadingList(prevState => {
const newState = [...prevState];
newState[index] = false;
return newState;
});
};
```
在需要显示 loading 的地方,可以根据对应的 index 来判断是否需要显示 loading,例如:
```
{loadingList[0] && <Loading />}
```
其中 Loading 是一个组件,用于显示 loading 状态。在需要触发 loading 的地方,可以调用 handleLoading 和 handleLoaded 方法来更新对应的 loading 状态。
相关问题
react 数组ComponentLoader
如果你想要加载一个包含多个组件的数组,你可以使用 React 中的 `ComponentLoader`。以下是一个使用 TypeScript 的示例:
```tsx
import React, { ComponentType, Suspense } from 'react';
type ComponentLoaderProps = {
components: Array<() => Promise<{ default: ComponentType<any> }>>;
};
const ComponentLoader: React.FC<ComponentLoaderProps> = ({ components }) => {
return (
<Suspense fallback={<div>Loading...</div>}>
{components.map((loadComponent, index) => {
const Component = React.lazy(loadComponent);
return <Component key={index} />;
})}
</Suspense>
);
};
```
在上面的示例中,我们定义了一个名为 `ComponentLoader` 的函数组件,它接受一个包含异步加载组件函数的数组 `components`。我们使用 `React.lazy` 和 `Suspense` 来异步加载每个组件,并在加载过程中显示一个加载中的提示。
你可以通过将需要加载的组件函数作为 `components` 数组的元素来使用 `ComponentLoader` 组件。例如:
```tsx
const components = [
() => import('./components/Component1'),
() => import('./components/Component2'),
() => import('./components/Component3'),
];
const App: React.FC = () => {
return (
<div>
<h1>My App</h1>
<ComponentLoader components={components} />
</div>
);
};
```
在上面的示例中,我们定义了一个 `components` 数组,其中包含三个异步加载组件的函数。然后,我们将 `components` 数组传递给 `ComponentLoader` 组件。
当 `ComponentLoader` 渲染时,它将遍历 `components` 数组并动态加载每个组件。你可以根据自己的需求在 `ComponentLoader` 组件中进行修改和扩展。
希望对你有所帮助!如果你有任何进一步的问题,请随时问我。
react 数组添加数据
在 React 中,如果要在数组中添加新的数据,需要使用setState()方法来更新组件的状态。具体步骤如下:
1. 创建一个新的数组或复制现有的数组;
2. 向新的数组中添加新的数据;
3. 使用setState()方法更新组件的状态,将新的数组赋值给原数组的状态属性。
以下是一个示例代码:
```
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
data: ['a', 'b', 'c']
};
}
handleClick = () => {
const newData = [...this.state.data, 'd'];
this.setState({ data: newData });
}
render() {
return (
<div>
<ul>
{this.state.data.map(item => <li key={item}>{item}</li>)}
</ul>
<button onClick={this.handleClick}>Add Data</button>
</div>
);
}
}
```
在这个示例中,我们创建了一个MyComponent组件,并将初始数据设置为 ['a', 'b', 'c']。当用户点击“Add Data”按钮时,我们会将新的数据 ['a', 'b', 'c', 'd'] 赋值给状态属性data,并使用setState()方法来更新组件的状态。