useSelector 取出全局的数据
useDispatch 使用全局的方法
引入
import { useSelector, useDispatch } from "react-redux"
取出全局的数据
const list = useSelector((state: any) => state.userinfo.list)
全局的方法
const dispatch = useDispatch()
使用全局的方法
引入全局的方法
import { asyncdel, asyncinitlist, asyncadd } from "../action/useraction"
dispatch(asyncinitlist())
完整的代码
import React, { useState, useEffect } from 'react'
import { useSelector, useDispatch } from "react-redux"
import { asyncdel, asyncinitlist, asyncadd } from "../action/useraction"
export default function Test6() {
const [username, setusername] = useState("")
const [userpwd, setuserpwd] = useState("")
const list = useSelector((state: any) => state.userinfo.list)
const dispatch = useDispatch()
useEffect(() => {
dispatch(asyncinitlist())
}, [])
return (
<div>
用户名<input type="text" value={username} onChange={(e) => {
setusername(e.target.value)
}} />密码<input type="text" value={userpwd} onChange={(e) => {
setuserpwd(e.target.value)
}} />
<button onClick={() => {
dispatch(asyncadd({
username,
userpwd
}))
}}>新增</button>
<div className="table">
<div className="item">
编号
</div>
<div className="item">
用户名
</div>
<div className="item">
密码
</div>
<div className="item">
操作
</div>
</div>
{
list.map((item: any) => {
return (<div className="table" key={item.id}>
<div className="item">
{item.id}
</div>
<div className="item">
{item.username}
</div>
<div className="item">
{item.userpwd}
</div>
<div className="item" onClick={() => {
dispatch(asyncdel(item.id))
}}>
删除
</div>
</div>)
})
}
</div>
)
}