我正在使用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
访问组件的list属性?
答案 0 :(得分:0)
考虑将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 />
数组。