假设我有下面的组件。这个脚本变得非常大,我想把我的doSomething函数放到另一个脚本中。
然而,调度只能用于React组件
import { useSelector, useDispatch } from "react-redux";
import axios from "axios";
import { toggle_progress_bar } from "../../actions/toggle_progress_bar";
import { set_progress } from "../../actions/set_progress.js";
export default function Example ({}){
const dispatch = useDispatch();
const doSomething = ()=>{
dispatch(set_progress(1))
dispatch(toggle_progress_bar())
}
const handlePress =()=>{
doSomething()
}
return(
<p onClick={handlePress)>just an example </p>
)
}
我试过
请注意,值1只是一个示例。该值可能来自doSomething函数中的axios请求等
export const doSomething = (toggle_progress_bar, set_progress) =>{
toggle_progress_bar()
set_progress(1)
}
import { useSelector, useDispatch } from "react-redux";
import axios from "axios";
import { toggle_progress_bar } from "../../actions/toggle_progress_bar";
import { set_progress } from "../../actions/set_progress.js";
import {doSomething} from "./doSomething.js"
export default function Example ({}){
const dispatch = useDispatch();
const handlePress =()=>{
doSomething(dispatch(toggle_progress_bar()),dispatch(set_progress()))
}
return(
<p onClick={handlePress)>just an example </p>
)
}
但我犯了各种错误。
正确的方法是什么?
export const doSomething = (toggle_progress_bar, set_progress) =>{
const dispatch = useDispatch();
return () => {
dispatch(toggle_progress_bar());
dispatch(set_progress(1));
};
}
然后称之为doSomething((
您可以尝试将dispatch作为参数传递。