虽然控制台显示在 class 访问时定义,但访问时道具未定义

Props undefined on access although console shows defined on class access

我正在参加一个 class 的课程,在那里我必须建立一个网站(我是前端的新手!),但我的教授和助教无法帮助我解决这个问题(React Component , JavaScript).

一个观察结果是,在 render() 函数中,props 是 始终定义的 。起初我以为它可能没有被安装或某些条件渲染问题,但 String prop 工作的事实可能会反驳这个问题?我也尝试过使用 <Stock ticker={String(stock.ticker)}/> 以防未传递 String ,但控制台已经显示该变量是 String 道具。 另一个奇怪的观察是,当我更新我的代码并在 npm start 期间保存它时,作为 prop 的变量突然被定义。页面的刷新使其在此之后再次未定义。硬编码 variables/downloaded json 文件也完全可以正常工作。

部分组件:

class Stock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      // some stuff here
    }
  }

  componentDidMount() {
    this.getStock();
  }

  getStock() {
    const key = secretstuff;
    let stock = this.props.ticker;
    console.log(this); // props says defined on console here
    console.log(this.props); // props is undefined on console here
    let call = `https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol=${stock}&outputsize=compact&apikey=${key}`;

父页面:

    class Page extends React.Component {
        constructor(props) {
          super(props);
          this.state = {
            stock: {}
          }
        }
      
        componentDidMount() {
          this.getStock();
        }
      
        getStock() {
           const symbol = this.props.match.params.id; // this part works
           // some fetch code, works completely fine to show on page
        }
      
        render() {
            let stock = this.state.stock;
            return (
  <div>
      <h1>{stock.ticker}</h1> // WORKS
         <h2>{stock.name}</h2> // WORKS
             </div>
                <div>
                    <Stock ticker={stock.ticker}/> // DOESN'T WORK!
                           ...... etc ............

你可能用错了this。 将此添加到构造函数中以绑定:

this.getStock= this.getStock.bind(this);

您未包含的 'fetch code' 可能是异步工作的。

这意味着您的组件将至少渲染两次,一次在 getStock 完成之前,一次之后。