【发布时间】:2019-04-15 08:00:24
【问题描述】:
我正在使用 Gatsby 构建我的网站,并尝试在用户单击课程标题时更改 Plyr 组件的 URL 属性。现在 URL 设置在 this.state 中,数据从 GraphQL 查询拉到 Contentful。
这是一个现场版本:https://brave-jepsen-d8ae28.netlify.com/courses/my-first-course
我创建了一个handleChange 函数来使用event.target.id 设置状态,但是一旦我单击课程段落标签,它就会返回错误。知道发生了什么吗?我测试了事件 ID 是用 console.log(event.target.id) 捕获的,而且确实如此,所以我假设一旦我尝试设置状态,它就会再次渲染组件。
感谢任何帮助!
import React, { Component } from 'react'
import { Link, graphql } from 'gatsby'
import Layout from '../components/layout'
import Plyr from 'react-plyr'
import '../components/plyr.css'
// On click, set the value of that elements video url to video player url value
class CourseTemplate extends Component {
constructor(props) {
super(props);
this.state = {
url: props.data.contentfulCourse.featureVideo
};
this.handleChange = this.handleChange.bind(this);
};
handleChange(event) {
event.stopPropagation();
// console.log(event.target.id)
this.setState(prevState => ({
url: event.target.id
}));
}
render() {
const courseContent = this.props.data.contentfulCourse
return (
<Layout>
<Plyr key={this.state.url} type="vimeo" videoId={this.state.url}/>
<p>{this.state.url}</p>
<h1>{courseContent.title}</h1>
<p>{courseContent.shortDescription}</p>
<div>
{courseContent.teachers.map(teacher => (
<div key={teacher.id}>
<p>by <Link to={`/teachers/${teacher.id}`}>{teacher.name}</Link></p>
</div>
))}
</div>
<div>
{courseContent.lessons.map(lesson => (
<div key={lesson.lessonVideo}>
<p onClick={this.handleChange} id={lesson.lessonVideo}>{lesson.title}</p>
</div>
))}
</div>
</Layout>
)
}
};
export default CourseTemplate
export const query = graphql`
query CourseTemplate($id: String!) {
contentfulCourse(id: {eq: $id}) {
title
shortDescription
featureVideo
slug
teachers {
id
name
}
lessons {
id
title
lessonVideo
slug
}
}
}
`
我收到的错误:
Warning: This synthetic event is reused for performance reasons. If you're seeing this, you're accessing the property 'target' on a released/nullified synthetic event. This is set to null. If you must keep the original synthetic event around, use event.persist().
TypeError: Cannot read property 'id' of null at ProxyComponent.eval
【问题讨论】:
-
“一旦我点击它就会返回错误” - 你能告诉我们错误吗?
-
我在brave-jepsen-d8ae28.netlify.com/courses/my-first-course 上添加了一个实时示例,我得到了
TypeError: Cannot read property 'id' of null在本地主机上,我在一个已发布/无效的合成事件上得到了一个更长的错误synthetic event is reused for performance reasons. If you're seeing this, you're accessing the propertytarget`。这设置为空。如果您必须保留原始合成事件,请使用 event.persist()` 加上TypeError: Cannot read property 'id' of null -
Using event.target with React components 的可能重复项 - 您的问题是由 React 使用的合成事件引起的。
this.setState是异步的,所以当event.target.id被调用时event.target不能再被安全访问。
标签: javascript reactjs graphql gatsby