reactjs - 如何访问组件状态内容?
问题描述
我正在使用 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
?
解决方案
考虑将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 />
推荐阅读
- java - 使用 JDK 16 运行 Beam 管道失败
- php - SMTP 连接()失败。PHPMailer
- sql-server - 使用 SSIS 包将数据从 Oracle 传输到 SQL Server 时的性能问题
- xamarin - Xamarin.Forms 上的默认数字键盘,但允许文本(跨平台)
- reactjs - 这是存储子集合的正确方法吗?
- sql-server - 如何使用 Transact-SQL 查询获取默认数据库名称?
- data-structures - 二叉树的空指针排列
- javascript - 如何在 ng-map (AngluarJS) 中为我的信息窗口添加悬停效果?
- vb.net - Selenium MoveByOffset 只工作一次
- python - TypeError:“numpy._DTypeMeta”对象不可下标