我有来自下面的react组件,问题是当检测到onClick事件时它不会自动呈现(触发handleClick函数)。
如果我写这个.forceUpdate(),那么它的工作正常。这应该不正常,没有它就应该正常工作。
import React from 'react';
import Loading from './Loading';
import CameraStore from "../stores/CameraStore";
import * as CameraActions from "../actions/CameraActions";
class LocationCameras extends React.Component {
constructor(props){
super(props);
this.state = {
updating: false
};
this.handleClick = this.handleClick.bind(this)
}
handleSwitch(){
}
handleClick(){
if(this.state.updating == false){
this.state.updating = true;
} else if (this.state.updating == true) {
this.state.updating = false;
}
console.log(this.state.updating);
this.forceUpdate();
}
render(){
var that = this;
return(
<div className="cameras">
<div className="panel panel-default">
<div className="panel-heading">
Client: {this.props.locationName}
<span className='camera--make-updates' onClick={this.handleClick} >
Update
</span>
</div>
<div className="panel-body">
{
this.props.cameras.map(function(camera,index){
if (camera.disabled !== "1"){
var statusClassName;
var checkStatus;
if (camera.status == 1){
var statusClassName = 'location--camera active';
checkStatus = true;
}
else {
var statusClassName = 'location--camera disabled';
checkStatus = false;
}
var handleSwitch = function(event){
var cameraId = camera.cameraId;
that.handleSwitch(event, cameraId, index);
}
return (
<div className={statusClassName} key={camera.cameraId}>
{
that.state.updating == true ? (
<div className="camera--switch">
<input type="checkbox" id={'switch' + camera.cameraId} defaultChecked={checkStatus} onChange={handleSwitch} className="switch--input"/>
<label htmlFor={'switch' + camera.cameraId} className="switch--label"></label>
</div>
) : (
<div className="camera--status"></div>
)
}
<div className="camera--name-id">
{ camera.name !== '' ? (
camera.name
) : (
'#' + camera.cameraId
)
}
</div>
</div>
)
}
}
)
}
</div>
</div>
</div>
)
}
}
module.exports = LocationCameras;
答案 0 :(得分:3)
请read the React documentation:
正确使用状态
关于
setState()
,您应该了解三件事。不要直接修改状态
例如,这不会重新渲染组件:
// Wrong this.state.comment = 'Hello';
相反,请使用
setState()
:// Correct this.setState({comment: 'Hello'});
您可以指定
this.state
的唯一位置是构造函数。[...]
答案 1 :(得分:2)
使用this.setState({updating: false})
insted this.state.updating = false;
,组件将重新呈现;
要关注@Felix评论,最好将您的函数句柄更改为
handleClick(){
this.setState({ updating: !this.state.updating })
}