【问题标题】:Cannot use this.props or set this.state in function outside Render不能在 Render 之外的函数中使用 this.props 或设置 this.state
【发布时间】:2020-11-12 23:17:21
【问题描述】:

第一个帖子和新的反应。

我遇到了一个问题,当我尝试在渲染外部的函数中使用 prop 时,它是 undefined,而当我尝试使用它来设置状态值时,它不起作用。

我已经阅读并找到了很多答案,主要是所有函数都应该绑定到类或使用箭头方法,所以当在函数内部引用this 时,它指的是类。

这些似乎都不起作用。

任何帮助将不胜感激。

下面是我正在使用的代码。

我从另一个组件调用EntryForm 组件,传递userDetails.Id 中的值5。

export interface UserDetails {
    Id: string;
}

export interface IProps {
    userDetails: UserDetails
}

export interface IState {
    combinedURL: string;
}

export default class EntryForm extends React.Component<IProps, IState> {

    constructor(props : IProps) {
        super(props);
        this.state = {
            combinedURL: 'MonkeyFace12' as string
        };
        this.createCombinedURL = this.createCombinedURL.bind(this);
    } 

    async createCombinedURL() {
        try {
            this.setState({ combinedURL: 'This is the Start of the URL followed by ' + this.props.userDetails.Id });
        } catch (e) {
            console.log("Error setting CombinedURL");
        }
    }

    async componentDidMount() {
        try {
            await this.createCombinedURL();
        } catch (error) {
        }
    }

    render() {
        return (
            <>
                <FormGroup row>
                    <Label
                        sm={1}>
                        Client
                    </Label>
                </FormGroup>

                <Button color="primary" type="submit">
                    Sign in
                </Button>
            </>
        );
    }
}

当我检查 this.state.CombinedURL 的值时,它仍然是 MonkeyFace12。

函数CreateCombinedURL 似乎完全没有影响。

【问题讨论】:

  • 所以如果我正确地让你说当你调用 this.setate 时它不起作用?最后,如果您是 React 新手,为什么不使用纯 JavaScript,直到您对 React 感到满意,而不是添加 TypeScript。
  • 您好,非常感谢您的回复。是的,当它运行命令时 this.setState({ combinedURL: '这是 URL 的开始,后跟 ' + this.props.userDetails.Id });它不设置组合 URL 状态。它保持为 MonkeyFace12。同样在调试期间,this.props.userDetails.Id 的计算结果为“未定义”。
  • 我明白你在说什么,但是当你刚接触 React 时,建议不要尝试将 TypeScript 添加到你只是让自己陷入困境的组合中

标签: reactjs typescript state this react-props


【解决方案1】:

不久前我和你一样。实际上,我发现在我遇到的很多情况下,使用箭头函数可以使日志更平滑,而且我来自 Java,其中类是关键。

在我看来,使用箭头函数和钩子看起来也更整洁。您不必担心“这个”。关键字。 Hooks 是非常棒的工具,它也取代了一些生命周期方法。下面只是一个例子,说明它可以变得多么清洁。


import React, { FC, useState } from 'react'

interface IProps {
   username: string
}

const EntryForm: FC<IProps> = ({username}) => {
   const [combinedURL, setCombinedURL] = useState('Start of the URL here +')//sets up state for you without extra work
   
   useEffect(() => {
      //do something to the state
      setCombinedURL(combinedURL + username)
   }, [])//This dependency array determines when this method fires. Empty means it runs only once.

   return(
      <div>
         This is the combined URL {combinedURL}
         <input type='text' onChange={e => {
            setCombinedURL(e.target.value); //Or whatever else you want to happen.
         }}>
      </div>
   )

}

【讨论】:

  • 顺便说一句,在其中使用函数也很容易。一个新手到另一个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-27
  • 1970-01-01
  • 1970-01-01
  • 2017-04-08
  • 2019-06-10
  • 1970-01-01
  • 2014-09-27
相关资源
最近更新 更多