如何在功能组件中立即更新反应状态?

How to update react state immediately in functional component?

我在 react.useEffect 中有很多逻辑,我想在 props.match 发生这样的变化时更新状态:

const [ start, setStart] = useState(0);
const [ end, setEnd] = useState(5);
React.useEffect(()=>{
if (!subcategory && !location && !search) {
                setStart(0);
                setEnd(5);
                if (url.search) {
                        Axios.post(`http://localhost:5000/getAll${url.search}`)
                            .then((res) => {
                                setLen(res.data.length);
                                const sliced = res.data.slice(props.start, props.end);
                                props.fetchData(sliced);
                                setStart(end);
                                setEnd(prev=> prev + 5);
                            })
                } else {
                        Axios.post('http://localhost:5000/getAll')
                            .then((res) => {
                                setLen(res.data.length);
                                const sliced = res.data.slice(props.start, props.end);
                                props.fetchData(sliced);
                                setStart(end);
                                setEnd(prev=> prev + 5);
                            })
                }
                return undefined;
            }
        },
        [ props.match ]
    );

为了让我的逻辑正常工作,我需要按顺序让开始和结束状态都等于 0 和 5,并且它总是在 axios 获取它们之前更新它们。

我试过使用另一个 useEffect,但没有用。我也不想使用 class 组件。

如何在功能组件中立即更新状态?

要立即使用 useEffect,类似于 class 生命周期 componentDidMount 使用 useEffect(()=>{},[]) 依赖数组中没有任何内容。

否则你需要传入你依赖的所有外部变量。开始,结束,

你第一次使用 useState 似乎是多余的,因为你已经将它们设置为 0 和 5。每个 props.match 都会 re-set useState

React.useEffect(()=>{
if (!subcategory && !location && !search) {
            setStart(0); // redundant
            setEnd(5); // redundant

我确实通过两个像这样的 useEffects 解决了这个大问题:

    const [ start, setStart ] = useState(0);
    const [ end, setEnd ] = useState(5);
    const [ urlChanged, setUrlChanged ] = useState(false);

    useEffect(
        () => {
            setStart(0);
            setEnd(5);
            setUrlChanged((prev) => !prev);
        },
        [ props.match ]
    );

    useEffect(
        () => {
            // logic using the latest end and start states
        },
        [ urlChanged ]
    );

奇怪的是,在 Whosebug 上从来没有人像我那样回答过这个问题,因为每个人都说要使用 class 组件 this.setState({state : '' , callback function}) 。