首页 > 解决方案 > 如何访问组件状态内容?

问题描述

我正在使用 React Slick 库来创建轮播组件。在构造函数中,我定义了以下状态:

class ArticlesContainer extends Component {
  constructor(props) {
    super(props);

    this.state = {
      lists: [],
      settings: {
        dots: true,
        infinite: false,
        speed: 500,
        arrows: true,
        slidesToShow: 1,
        slidesToScroll: 1,
      },
    };
  }
}

在一个事件之后,我这样调用 this.setState :

this.setState(prevState => ({
  lists: response.data,
  settings: {
    ...prevState.settings,
    customPaging: function(i) {
      console.log(this.state.lists);

      return <a>{i}</a>;
    },
  },
}));

问题是当我打电话时console.log(this.state.lists),它说它是未定义的。如何访问我的组件的列表属性,从customPaging

标签: reactjs

解决方案


考虑将customPaging回调修改为箭头函数,而不是“常规函数”:

this.setState(prevState => ({
  lists: response.data,
  settings: {
    ...prevState.settings,
    customPaging: (i) => {

      // "this" will now correspond to the component instance
      // meaning that this.state will be the current state of
      // your outer ArticlesContainer component
      console.log(this.state.lists);

      return <a>{i}</a>;
    },
  },
}));

这将导致customPaging回调的上下文成为您的组件的上下文,从而允许您访问组件实例的state.lists数组。<ArticlesContainer />


推荐阅读