跨组件状态管理总结

小场面

状态提升

兄弟组件之间传值(共享状态),需要状态提升,示例:

Ceshi3 和 Ceshi4 之间需要共享 value 值,所以将 value 值提升到他俩的公共父组件 Ceshi2 中:

Ceshi2:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import Ceshi3 from "./ceshi3"
import Ceshi4 from "./ceshi4"
import { useState } from "react"

const Ceshi2 = () => {
const [value, setValue] = useState("") // 状态提升
return (
<div>
<Ceshi3 value={value} setValue={setValue} />
<Ceshi4 value={value} setValue={setValue} />
</div>
)
}
export default Ceshi2

Ceshi3:

1
2
3
4
5
6
7
8
9
10
11
import { Input } from "antd"

type InputType = {
value: string
setValue: (value: string) => void
}

const Ceshi3 = ({ value, setValue }: InputType) => {
return <Input value={value} onChange={e => setValue(e.target.value)} />
}
export default Ceshi3

Ceshi4:

1
2
3
4
5
6
7
8
9
10
import { Input } from "antd"

type InputType = {
value: string
setValue: (value: string) => void
}
const Ceshi4 = ({ value, setValue }: InputType) => {
return <Input value={value} onChange={e => setValue(e.target.value)} />
}
export default Ceshi4

组合组件

对于上面状态提升的示例,只是将需要共享的数据进行提升,可以将组件进行提升,也就是组合组件:

Ceshi2:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import Ceshi3 from "./ceshi3"
import Ceshi4 from "./ceshi4"
import { useState } from "react"
import { Input } from "antd"

const Ceshi2 = () => {
const [value, setValue] = useState("") // 状态提升
const InputCeshi = <Input value={value} onChange={e => setValue(e.target.value)} />
return (
<div>
<Ceshi3 input={InputCeshi} />
<Ceshi4 input={InputCeshi} />
</div>
)
}
export default Ceshi2

Ceshi3:

1
2
3
4
const Ceshi3 = (props: { input: JSX.Element }) => {
return props.input
}
export default Ceshi3

Ceshi4:

1
2
3
4
const Ceshi4 = ({ input }: { input: JSX.Element }) => {
return input
}
export default Ceshi4

缓存状态

react-query

swr

客户端状态

url

Context

react 框架原生提供

示例:

1

Redux

第三方,最经典的,如果是大型应用,需要比较复杂的状态管理,推荐使用。

需要维护 一个全局状态树。