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

时间:2020-09-15 20:09:53

标签: javascript reactjs react-hooks react-state

react.useEffect中包含大量逻辑,并且每当prop.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,但是没有用。我也不想使用类组件。

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

2 个答案:

答案 0 :(得分:0)

我确实通过具有两个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 ]
    );

奇怪的是,没有人以我解决问题的方式在stackoverflow上回答这个问题,因为每个人都说要使用类组件this.setState({state:``,callback function})。

答案 1 :(得分:-1)

要立即使用useEffect,类似于类生命周期componentDidMount,请使用useEffect(()=>{},[]),在依赖项数组中不包含任何内容。

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

您第一次使用useState似乎是多余的,因为您已经将它们设置为0和5。每个props.match将重新设置useState

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