V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
qwertty01
V2EX  ›  问与答

救救孩子吧, React 函数父子组件数据更新流程没有搞明白

  •  1
     
  •   qwertty01 · 2020-12-11 16:27:45 +08:00 · 674 次点击
    这是一个创建于 1203 天前的主题,其中的信息可能已经有所发展或是发生改变。
    
    function App() {
        const [data, setData] = useState([])
        const [sqlType, setSqlType] = useState("ALL")
    
        useEffect(() => {
            axios.get(updateSql_findAll, {
                params: {
                    actualSqlType: sqlType
                }
            }).then(response => {
                console.log(response.data[0].second)
                setData(() => {
                    return response.data
                })
            })
        }, [sqlType])
    
        const onSqlTypeSelect = (event) => {
            setSqlType(event.target.value)
        }
    
        return (
            <div>
                <select onChange={(event => onSqlTypeSelect(event))}
    
                        style={{width: "200px"}}>
                    <option value={"ALL"}>ALL</option>
                    <option value={"SELECT"}>SELECT</option>
                </select>
                <Test data={data[0]}/>
            </div>
        )
    }
    
    const Test = (props) => {
        console.log(props.data.second)
        return (<div>
            Test
        </div>)
    }
    
    

    我想的更新流程是,我选择 Sql 类型,useEffect 调用,data 数据变化,重渲染子组件 然而实际的流程是,我选择 Sql 类型,重新渲染了子组件,useEffect 调用,data 数据变化,子组件没有进行渲染

    1 条回复    2020-12-11 16:38:43 +08:00
    qwertty01
        1
    qwertty01  
    OP
       2020-12-11 16:38:43 +08:00
    ```
    function App() {
    const [data, setData] = useState([])
    const [sqlType, setSqlType] = useState("ALL")

    useEffect(() => {
    axios.get(updateSql_findAll).then(response => {
    console.log("use effect 调用")
    setData(() => {
    return response.data
    })
    })
    }, [sqlType])

    const onSqlTypeSelect = (event) => {
    setSqlType(event.target.value)
    }

    return (
    <div>
    <select onChange={(event => onSqlTypeSelect(event))}

    style={{width: "200px"}}>
    <option value={"ALL"}>ALL</option>
    <option value={"SELECT"}>SELECT</option>
    </select>
    <Test/>
    </div>
    )
    }

    const Test = () => {
    console.log("Test 渲染调用")
    return (<div>
    Test
    </div>)
    }
    ```
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1543 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 372ms · UTC 17:05 · PVG 01:05 · LAX 10:05 · JFK 13:05
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.