簡體   English   中英

子組件中的 useEffect 觸發父 state 更改但具有舊父 state

[英]useEffect in child component triggers on parent state change but has old parent state

我有一個父組件(IssueWindow),它將 state(問題)傳遞給子組件(IssueSidebar)。 當我在孩子中進行 state 更改時,我想通過調用父 function 來更新父 state。 然后我在孩子中有一個 useEffect 設置來檢測這個父 state 更改,然后相應地更新下拉列表。

我能夠成功地改變孩子並讓它改變父母 state。 我什至可以在父母的 state 發生變化時觸發孩子的 useEffect 但是孩子在這個 useEffect 中的 state 實際上是以前的值而不是來自父母的最新值。

知道為什么會這樣嗎?

<!-- language: react -->
export default function IssueWindow() {
    //Load initial issue state
    useEffect(() => {
        return () => {
            axios.get(`${endpoints.issues}/${issueId}`)
                .then(response => {
                    setIssue(response.data);
                })
                .catch(error => console.error(`Error: ${error}`))
        };
    }, []);
    //Fires when issue changes in child components
    const updateIssue = (updateIssue) => {
        axios.post(`${endpoints.issues}`,updateIssue)
            .then(response => {
                setIssue(response.data);
            })
            .catch(error => console.error(`Error: ${error}`))
    }
    return (
        <Container className={"issue"} sx={{display:"flex", direction:"row"}}>
            <Grid container direction="row">
                <Grid container item xs={8} direction={"column"}>
                    {issue && <IssueDetails issue={issue} updateIssue={updateIssue}/>}
                    {issue && <IssueComments issue={issue} updateIssue={updateIssue}/>}
                </Grid>
                <Grid container item xs={4} direction={"column"}>
                    {issue && <IssueSidebar issue={issue} updateIssue={updateIssue}/>}
                </Grid>
            </Grid>
        </Container>
    )
}

export default function IssueSidebar(props) {
    //Store input value lists
    const [inputListValues, setInputListValues] = useState({});
    //Dropdown value states
    const [priority.InputValue, setStateInputValue] = useState(1);
    
    //Initial dropdown values
    useEffect(() => {
        return () => {
            //PRIORITY
            axios.get(`${endpoints.issues}/${props.issue.issueId}/state`)
                .then(response => {
                    setInputListValues(prevState => {
                        return {
                            ...prevState,
                            priority : response.data
                        }
                    })
                    setPriorityInputValue(response.data.indexOf(props.issue.priority))
                })
                .catch(error => console.error(`Error: ${error}`))
        };
    }, []);

    useEffect(() => {
        return () => {
            if (inputListValues.state && inputListValues.priority){
                //props.issue has old value here!
                setStateInputValue(inputListValues.state.indexOf(props.issue.state))
            }
        };
    }, [props.issue]);

    //Select dropdowns
    const handleDropdownChange = (e) =>{
        props.updateIssue({
            ...props.issue,
            [e.target.name] : inputListValues[e.target.name][e.target.value]
        });
    }
    
    return (
    <Grid className={"issue-sidebar"} container direction={"column"}>
        {/*PRIORITY*/}
        <Grid container direction={"row"} className={"issue-sidebar__row"}>
            <Grid><Typography className={"label"}>Priority:</Typography></Grid>
            { inputListValues.priority && (<Select name={"priority"} defaultValue={1} value={priorityInputValue} onChange={handleDropdownChange}>
                {inputListValues.priority.map((priority, index) => <MenuItem value={index} key={index}>{priority}</MenuItem>)}
            </Select>)}
        </Grid>
    </Grid>
    )
}

也許您應該從 useEffect 的清理 function 中移動代碼:

    useEffect(() => {
        // add here
        if (inputListValues.state && inputListValues.priority){
setStateInputValue(inputListValues.state.indexOf(props.issue.state))
        }

        return () => {
            // remove from here
        };
    }, [props.issue]);

來自反應文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM