[英]How can I rewrite part of the component to react hooks
告诉我,我想重写写在hooks上的生命周期的方法上的组件,但是它在这个地方并没有完全出来,它不能正常工作。 如何正确重写?
componentDidMount() {
this.updateUser();
}
componentDidUpdate(prevProps){
if (this.props.userId !== prevProps.userId) {
this.updateUser();
console.log('update')
}
}
updateUser = () => {
const {userId} = this.props;
if (!userId) {
return;
}
this.onUserLoading();
this.API
.getUser(userId)
.then(this.onUserLoaded)
.catch(this.onError)
我已经修改了反应新的钩子,
componentDidMount
表示useEffect(()=>{},[])
componentDidUpdate
表示useEffect((prev)=>{},[YOUR UPDATE DATA VARIABLE])
现在看起来像这样,您的功能如下所示,
updateUser = () => {
if (!userId) {
return;
}
this.onUserLoading();
this.API
.getUser(userId)
.then(this.onUserLoaded)
.catch(this.onError)
}
这将被转换为功能组件,
const [userId,setUserId] = useState(props.userId); // way 1
//const userId = {props}; // way 2
useEffect((prevProps)=>{
updateUser();
if(userId !== prevProps.userId){
updateUser();
console.log('update')
}
},[userId, updateUser])
请注意,效果取决于 updateUser 并且传递给 useEffect 的回调没有任何参数。 这是一个工作示例:
const User = React.memo(function User({ userId }) { const [userResult, setUserResult] = React.useState(""); //create this function only on mount const onUserLoaded = React.useCallback( (result) => setUserResult(result), [] ); //do not re create this function unless userId changes const onUserLoading = React.useCallback(() => { setUserResult(`user loading for ${userId}`); setTimeout( () => onUserLoaded(`result for user:${userId}`), 1000 ); }, [userId, onUserLoaded]); //do not re create this function unless userId // or onUserLoading changes, onUserLoading only // changes when userId changes const updateUser = React.useCallback(() => { if (!userId) { return; } onUserLoading(); }, [onUserLoading, userId]); //run the effect when updateUser changes // updateUser only changes when userId changes React.useEffect(() => updateUser(), [updateUser]); return <div>user result:{userResult}</div>; }); const App = () => { const [userId, setUserId] = React.useState(1); return ( <div> <button onClick={() => setUserId(userId + 1)}> Change User ID </button> <User userId={userId} /> </div> ); }; ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script> <div id="root"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.