我正在使用React Slick库来创建carousel组件。在构造函数中,我定义了以下状态:
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访问组件的lists属性
发布于 2018-12-27 06:40:02
考虑将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回调的上下文成为您的组件的上下文,从而允许您访问<ArticlesContainer />组件实例的state.lists数组。
https://stackoverflow.com/questions/53937465
复制相似问题