我的setState没有't chance the state in the handleClick event handler. I'确保handleClick有效,因为它记录了参数 .
我是React的新手,所以我必须忽略一些东西 . 这是否意味着我的handleClick函数有问题?
任何建议都会非常感激!
import React from 'react';
import './Projects.css';
import Footer from '../../Components/Footer/Footer.js';
import ProjectPage from
'../../Components/ProjectPage/ProjectPage.js';
import { Redirect, Link } from 'react-router-dom';
class Projects extends React.Component {
constructor(props) {
super(props);
this.state= {
title: "kaufmann house",
content: "charles",
}
this.getImages = this.getImages.bind(this);
}
getImages() {
var VisibilitySensor = require('react-visibility-sensor');
return this.props.projectList.map((post,index) =>
<div>
<div className="projects">
<VisibilitySensor onChange={isVisible =>
this._onChange(isVisible, post.title)}>
<img key={post.id} src={post.featureImage}
className='projectImage' alt='projectImage' onClick= .
{this.handleClick.bind(this, post.content)}/>
</VisibilitySensor>
</div>
</div>
)
}
_onChange = (isVisible, param) => {
isVisible && this.setState({title: param});
};
handleClick = (param) => {
console.log(param);
this.setState({content: param});
};
render() {
return (
<div>
<Link to={{pathname: `/ProjectPage/${this.state.title}`,
state: {
info: `${this.state.content}`}
}}>{this.getImages()}</Link>
<Link to={{pathname: `/ProjectPage/${this.state.title}`,
state: {
info: `${this.state.content}`}
}}>
<Footer title={this.state.title}/>
</Link>
</div>
)
}
}
export default Projects;
2 回答
我建议进行以下更改:
1)移动var VisibilitySensor = require('react-visibility-sensor');到文件的顶部以保持组件清洁
2)关于你的点击处理程序,使用bind创建处理函数是一个不好的做法,因为这可能会导致性能问题,因为将在每个渲染上创建一个新函数 . 您可以使用箭头功能并设置data- [attribute]以向组件添加数据
您的
state
包含 Headers 和内容 . 你必须setState
如下 . 否则,您的新state
将无法正确更新,因为您替换了整个state
对象 .