當 props 發生變化時,我在更新組件時遇到了問題。我使用 useEffect 讓它工作,但不確定這是否是解決我的問題的正確方法。這是我的代碼:import * as React from "react";import "./styles.css";const InputWithDefaultValue = (props: any) => { const { value } = props; //had to add this to get my component to rerender when the button in App-Component was pressed React.useEffect(() => { setText(value); }, [value]); const [text, setText] = React.useState(value); return ( <input value={text} onChange={(e) => setText(e.currentTarget.value)} ></input> );};export const App = () => { const [value, setValue] = React.useState("Foo"); return ( <div className="App"> <InputWithDefaultValue value={value} /> <button onClick={() => setValue(Math.random().toString())}>Update</button> </div> );};export default App;我在想,當我更新InputWithDefaultValue的道具時,它會被重新渲染。是使用 useEffect 讓組件重新呈現解決問題的正確方法,還是我找到了一些 hacky-solution?
我需要使用 useEffect 來重新渲染組件嗎?
qq_遁去的一_1
2023-02-24 16:44:49