我有下面的反應組件,問題是它不會在檢測到onClick事件(觸發handleClick函數)時自動呈現。React state not rerendering
如果我寫這個.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;
更好:整個函數體可以用'this.setState更換({更新:this.state.updating})' –
@Felix,當然,你是對的。我只是展示他如何調用重新渲染。 – Andrew