reactjs - setState 在 handleClick 中不起作用
问题描述
我的 setState 不会影响 handleClick 事件处理程序中的状态。我确定 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;
解决方案
this.state= {
title: "kaufmann house",
content: "charles",
}
您的state
包含标题和内容。你必须setState
喜欢下面。否则,您的 newstate
将无法正确更新,因为您替换了整个state
对象。
_onChange = (isVisible, param) => {
isVisible && this.setState({
...this.state,
title: param
});
};
handleClick = (param) => {
console.log(param);
this.setState({
...this.state,
content: param
});
};
推荐阅读
- windows - Cygwin:创建Windows通知并在单击通知时聚焦程序
- wordpress - windows 10中的流浪错误并且无法制作VM
- excel - Excel 不会输入混合日期
- r - R中的多文件处理,循环变量进行数据处理
- ssl - ActiveMQ:配置与 AD 的安全 LDAPS 连接
- python - 获取 ImportError:无法从 'verlat' 导入名称 'latest' 尝试使用 wappdrive 模块
- mongodb - MongoDB相同的索引错误与不同的字符串
- c# - 来自 Enum 的随机值不像我希望的那样工作
- terminal - 将 zsh 颜色与 dircolors 集成
- android - kotlin - 如何读取 json 数据?