首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何访问组件状态内容?

如何访问组件状态内容?
EN

Stack Overflow用户
提问于 2018-12-27 05:41:08
回答 1查看 40关注 0票数 1

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

代码语言:javascript
复制
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,如下所示:

代码语言:javascript
复制
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访问组件的lists属性

EN

回答 1

Stack Overflow用户

发布于 2018-12-27 06:40:02

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

代码语言:javascript
复制
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回调的上下文成为您的组件的上下文,从而允许您访问<ArticlesContainer />组件实例的state.lists数组。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53937465

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档