反应:未捕获的TypeError:无法读取未定义的属性“ i”

时间:2020-02-20 05:00:05

标签: javascript reactjs typeerror

我的代码有问题:

class Albs extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      i: 0,
      anh: this.props.hinhanh[this.state.i]
    };
    var hinhanh = ["1.png", "2.png", "3.png"];
    this.state.i = this.state.i.bind(this);
  }
  nextPic(){
    this.setState({i: this.state.i++});
  }
  backPic(){
    this.setState({i: this.state.i--});
  }
  render(){
    return(
      <div>
        <img src={this.state.anh}/>
        <br/>
        <button onClick={nextPic}>Next</button>
        <button onClick={backPic}>Back</button>
      </div>
    )
  }
}

ReactDOM.render(
  <Albs/>,
  document.getElementById('root')
);

在控制台中,它显示:Uncaught TypeError:无法读取未定义的属性“ i”。原因吗?

2 个答案:

答案 0 :(得分:0)

您需要像使用this那样将类this.state.i绑定到方法nextPic和backPic(我不认为这是必要的)

或者您可以使用此语法

nextPic = () => {
    this.setState({i: this.state.i++});
  }
  backPic = () => {
    this.setState({i: this.state.i--});
  }

答案 1 :(得分:0)

您犯了很多错误,请查看我的代码并进行比较。希望您能找到错误。

const data = [
  {
    _id: "5e4b1213e666de6628044139",
    product: "air-jordan-1-retro-high-unc-chicago-leather-w"
  },
  {
    _id: "5e4b121de666de662804413a",
    product: "nike-air-force-1-high-just-don-blue"
  },
  {
    _id: "5e4b1227e666de662804413b",
    product: "air-jordan-new-beginnings-pack-1-nike-air-ship"
  },
  {
    _id: "5e4b1246e666de662804413c",
    product: "nike-sb-dunk-low-strangelove-skateboards"
  }
];

const productsLine = (data, seperator = "\r\n") =>
  data.map(x => x.product).join(seperator);

console.log(productsLine(data));
console.log(productsLine(data, ", "));
  • 您可以将状态属性立即定义为类似class App extends Component { constructor(props) { super(props); this.state = { i: 0 }; var hinhanh = ["1.png", "2.png", "3.png"]; this.nextPic = this.nextPic.bind(this); this.backPic = this.backPic.bind(this); } componentDidMount() { this.setState({ anh: this.state.i}); } nextPic() { this.setState({ i: this.state.i++ }); console.log(this.state.i); } backPic() { this.setState({ i: this.state.i-- }); console.log(this.state.i); } render(){ return( <div> <img src={this.state.anh}/> <br/> <button onClick={this.nextPic}>Next</button> <button onClick={this.backPic}>Back</button> </div> ) } } j this.state = { i: 0, j: this.state.i}, here componentDidMount is undefined. So you need to use life cycle method setState`的状态。
  • 您需要绑定函数,否则需要使用箭头函数to