【问题标题】:React JS, Error is not defined no-undef when attempting to obtain first value from arrayReact JS,尝试从数组中获取第一个值时未定义错误
【发布时间】:2018-06-25 15:16:55
【问题描述】:

我试图从数组中输出一个值,但得到错误:array1 is not defined no-undef

代码片段

 constructor() {
        super();
        this.state = {  
          array1: [],
        }
      }

//代码 sn -p componentDidMount

componentDidMount(props) {
    this.setState({array1: [5, 12, 8, 130, 44] })
  }

//代码sn-p,函数

found = this.state.array1.find((element) => {
    return element > 10;
  }); 

代码 sn-p:

render(){
console.log(found);
}

箭头函数出现页面错误,请问可以帮忙吗?

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    你的构造函数应该改为

    constructor() {
        super();
        this.state = {
            array1: []
        }
    }
    

    您尚未将您的 array1 定义为状态。

    更新(根据 cmets 更新答案)

    constructor() {
        super();
        this.state = {
            array1: []
        }
        this.found = this.found.bind(this);
    }
    
    found() {
        return this.state.array1.find((element) => {
            return element > 10;
        }); 
    }
    
    render(){
        console.log(this.found());
    }
    

    【讨论】:

    • Vikas - 我发布问题时不小心删除了“this.state=”行;在我的函数中,我将“this.state”添加到“array1”,它现在反映了以下内容:this.state.array1.find ...但我收到以下错误:TypeError:无法读取未定义的属性“array1”。如果您有任何其他建议,请告诉我...谢谢
    • 知道了。 array1 被定义为一个状态,唯一的问题是this 超出了它的上下文。解决它的一种方法是found = (array1) => { return array1.find((element) => { return element > 10; }); } render(){ console.log(found(this.state.array1)); } P.S - 我还没有测试过代码
    • ...我得到错误 'found' is not defined no-undef 。 ...在 console.log(found(this.state.array1)); ...如果我删除找到,它不会返回任何内容...如果您有任何其他建议,请告诉我。谢谢
    • 应该是console.log(this.found(this.state.array1));
    【解决方案2】:

    没有构造函数,也没有绑定你的函数(感谢类字段)这是你渲染(不是 console.log)数组元素的方式。

    class Foo extends React.Component {
      state = { array: [] };
          
      componentDidMount() {
        this.setState({array: [5, 12, 8, 130, 44] })
      }
      
      // With some cheating.
      found = () =>
        this.state.array
        .map(el => el < 10 ? undefined : <p>{el}</p> );    
      
      // Maybe nicer one?
      foundAlternative = () => 
        this.state.array
          .filter( el => el > 10 )
          .map( el => <p>{el}</p>);
          
           
      render() {
        return (
          <div>{this.found()}</div>
        )
      }
    
    }
    
    ReactDOM.render(
      <Foo />,
      document.getElementById("root")
    );
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
    <div id="root"></div>

    【讨论】:

      猜你喜欢
      • 2015-04-14
      • 1970-01-01
      • 1970-01-01
      • 2023-02-04
      • 1970-01-01
      • 1970-01-01
      • 2019-12-15
      • 2019-12-05
      • 1970-01-01
      相关资源
      最近更新 更多