繁体   English   中英

如何从 React 中的子组件更新父组件(功能)

[英]How to update Parent component from Child component in React (Functional)

我有以下称为 RoomManagement 的功能组件。 在第一次渲染时,fetchRooms 被调用,它反过来使用数据库中的数据初始设置 state 变量。

我有一个名为 RoomManagementModal 的子组件,我在其中传递了我的 setLoading 和 fetchRooms function。

我在重新渲染父组件时遇到问题。 我单击子组件中的一个按钮(这会向数据库添加一些内容)。 因此,我试图通过再次调用props.fetch()来获取新数据,但这次来自子级,我认为这会触发父级上的 state 更改,但似乎并非如此。

如果可能的话,我似乎无法找到一种强制父组件再次渲染的方法

function RoomManagement() {

    const [rooms, setRooms] = useState([]);
    const [unavailableRooms, setUnavailableRooms] = useState();
    const [loading, setLoading] = useState(true);

    const fetchRooms = async () => {
        await getAllRooms().then((res) => {
            res.json().then(data => setRooms(data))
        });
        await getAllRoomsUnavailable().then((res) => {
            res.json().then(data => setUnavailableRooms(data[0]))
        })
        setLoading(false)
    }
    
    useEffect(() => {
        fetchRooms();
    }, []);
    
    return (.....
   <RoomManagementModal setLoading={setLoading} fetch={fetchRooms}/>
)

}
export default RoomManagement;
<Button
          onClick={() => {
            if (form.room_id && form.start && form.end) {
              createRoomUnavailable(form).then((res) => {
                if (res.status != 200 && res.status != 201) {
                  res.text().then((e) => setError(e));
                } else {
                  props.fetch()
                }
              });
            } else {
              setError("Missing required Room Id or date time.");
            }
          }}
        >
          Submit
        </Button>

父组件

1.Declare a state and a setter for the title or slug 2.Define a function to update the state 3.Pass that function down as props to the child component

子组件

1.定义一个 function 来处理和调用作为 props 传递的 function 2.来自父组件

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM