简体   繁体   English

如何重写组件的一部分以响应钩子

[英]How can I rewrite part of the component to react hooks

tell me, I want to rewrite the component written on the methods of the life cycle on hooks, but it does not come out exactly in this place, it does not work as it should.告诉我,我想重写写在hooks上的生命周期的方法上的组件,但是它在这个地方并没有完全出来,它不能正常工作。 How to rewrite it correctly?如何正确重写?

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)

i have modified with react new hooks,我已经修改了反应新的钩子,

componentDidMount means useEffect(()=>{},[]) componentDidUpdate means useEffect((prev)=>{},[YOUR UPDATE DATA VARIABLE]) componentDidMount表示useEffect(()=>{},[]) componentDidUpdate表示useEffect((prev)=>{},[YOUR UPDATE DATA VARIABLE])

this will look like this way now, your function is like below,现在看起来像这样,您的功能如下所示,

updateUser = () => {
  if (!userId) {
      return;
  }
  this.onUserLoading();
  this.API
          .getUser(userId)
          .then(this.onUserLoaded)
          .catch(this.onError)
}

this will be converted functional component,这将被转换为功能组件,

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])  

Please note that the effect depends on updateUser and the callback passed to useEffect does not get any arguments.请注意,效果取决于 updateUser 并且传递给 useEffect 的回调没有任何参数。 Here is a working example:这是一个工作示例:

 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.

相关问题 如何将异步 HOC 组件重写为 React Hooks? - How to rewrite async HOC component to the React Hooks? 我如何在 React 经典的 `class` 组件中使用 React hooks? - How can I use React hooks in React classic `class` component? 如何强制组件使用 React 中的钩子重新渲染? - How can I force a component to re-render with hooks in React? 如何从子组件反应钩子中仅更改 state 的一部分 - How to change only a part of the state from child component react hooks 如何将类组件重写为使用钩子的组件 - How to rewrite a class component to a component that uses hooks React native:如何将 class 组件代码转换为带有钩子的 function 组件? - React native : How can I turn the class component code into a function component with hooks? 我可以在 React 组件之外使用 React Hooks - Can I use React Hooks outside a React Component 如何防止我的功能组件使用 React 备忘录或 React 钩子重新渲染? - How can I prevent my functional component from re-rendering with React memo or React hooks? 在将新项目添加到数据库后,如何使用 React 钩子更新 React 中的组件? - How can I update component in React after adding a new item into the database, using react hooks? React挂钩-如何通过服务器端渲染将组件附加到侦听器? - React hooks - How can i attach a component to a listener with server side rendering?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM