我有一个切片文件,其中包含一个异步 thunk 函数,该函数根据 api 响应返回一个数组。其中一些数组元素是一些 i 标签,它们触发一些函数在另一个将调度此异步 thunk 的组件内执行某些操作。当此切片文件不是具有这些函数定义的组件的子级时,我不知道如何调用这些函数(handleShowForm 和 handleShowHistory)。我的意思是我无法通过道具或上下文传递它们。
我的 slice.js 文件:
export const getNomads = createAsyncThunk("applicant/getNomads", async(data) => {
const {
searchParam,
pageNum
} = data
let nomadObj = {
isPending: true,
bodyArray: []
}
await axios.get(`https://demo.khedmatashayer-kj.ir/api/v1/nomad/${pageNum}?${searchParam}`, config)
.then((response) => {
.
.
.
let array = [];
response.data && response.data.forEach((item) => {
array = [...array, [ < i className = "fa fa-edit edit"
onClick = {
() => handleShowForm(item)
} > < /i>, <
i className = "fa fa-file-text-o records"
onClick = {
() => handleShowHistory(item.name, item.nomad_id)
} > < /i>,
.
.
.
], ];
});
nomadObj = {
isPending: false,
bodyArray: array
}
})
return nomadObj;
})
const applicantSlice = createSlice({
.
.
.
.
}
})
我的组件:
const MyComponent = () => {
const handleShowForm = (arg) => {
.
.
}
const handleShowHistory = (arg1, arg2) => {
.
.
}
useEffect(() => {
dispatch(getNomads({
searchParam: '',
pagaNum: 1
}))
});
}
看起来你需要一个状态管理器来响应最流行的状态管理器是react context,react redux或zustand。
因此您需要在函数内操作相同的值。
例如:
const handleShowForm = (arg) => {
setVisible(true)
.
.
}
然后在 onClick 的 createAsyncThunk 中调用相同的方法:
onClick={() => setVisible(true}
其中 setVisible 是上下文公开的常量。
上下文:https://react.dev/reference/react/createContext
Zustand:https://github.com/pmndrs/zustand
这是一种方法,另一种方法是创建一个名为 helper.js 的新文件并在其中写入handleShowForm 和handleShowHistory。确保导出它们,以便能够在文件中调用它们。