【问题标题】:Can we assign a Typescript class to a useState field of a Functional Component in React?我们可以将 Typescript 类分配给 React 中功能组件的 useState 字段吗?
【发布时间】:2020-05-22 12:15:27
【问题描述】:

我正在浏览 this blog - useEffect complete guide topic 并考虑使用一个简单的 Typescript 类并更新状态,并查看 useEffect 的行为方式。

可以将 Typescript 类分配给 useState 变量吗??

您可以在CodeSandbox.io 中找到该示例的链接

如果 JSX...那么,如果它只是一个 ES6 类而不是 Typescript 怎么办?

【问题讨论】:

    标签: reactjs typescript use-state


    【解决方案1】:

    您正在将类的实例存储在状态中,但您从不更新它。

    您必须注意,即使您将项目添加到 stateHelper 类但实例没有更改,因此 useEffect 不会再次执行。

    但是,为了存储在整个组件实例范围内保持不变的实例,最好使用 useRef 而不是 useState

    const TypeScriptComponent: FunctionComponent = (props): JSX.Element => {
      // Creating an instance from a (Typescript) Class and assigning it to useState
      const stateHelper = useRef<StateHelper>(new StateHelper());
      const [list, setList] = useState<string[]>([]);
    
      // ........on button click
      const handleButtonClick = async () => {
        stateHelper.current.addList("Shwetha");
        // Calling an async data from the Typescript class this time
        const result = await stateHelper.current.fireData();
        if (result) {
          stateHelper.current.addList(result);
          const newList = stateHelper.current.getList();
          console.log("New list is: ", newList);
          setList(newList);
        }
      };
    
      useEffect(() => {
        stateHelper.current.addList("Pramod");
        const newList = stateHelper.current.getList();
        setList(newList);
        console.log("component did mount");
      }, []);
    
      return (
        <React.Fragment>
          <div>
            {list.length > 0 &&
              list.map((item: any, index: number) => <p key={index}>{item}</p>)}
            <button onClick={handleButtonClick}>Add Me</button>
          </div>
        </React.Fragment>
      );
    };
    
    export default TypeScriptComponent;
    

    【讨论】:

    • 绝对可以使用 useState,但由于您不需要更新功能,使用 useRef 会更容易理解
    【解决方案2】:

    谢谢大佬。有道理……!

    我之所以想到useState,是因为如果我们能有这样的东西

    const [customObj, setCustomObj] = useState({}); // primitive object
    

    ....为什么没有一个完全成熟的类实例

    const customObj = useState(new CustomClass())[0]; // fully fledged instances of a class
    

    这有意义吗?

    【讨论】:

      猜你喜欢
      • 2020-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-12
      • 2010-11-19
      • 2014-08-26
      • 2022-01-05
      • 2023-04-04
      相关资源
      最近更新 更多