ReactJS更新和显示正确值的正确方法是什么。
示例:我在数据库中显示屏幕上的数据。当我更改数据库中的值时,我想直接在屏幕上看到新值。
我有两个文件:
class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {
containers: []
};
}
componentDidMount() {
var self = this;
axios.get('http://reactlaravel.dev/container/count').then(function (response) {
self.setState({
containers: response.data
});
})
}
render() {
const containers = this.state.containers.map( (container, i) => <StockCount key={i} {...container} /> );
return (
<div>
{containers}
</div>
)
}
const Container = ({ name, total, current }) => (
<div>
<span>{name}</span>
<span>{total}</span>
<span>{current}</span>
</div>
);
ReactDOM.render(
<Parent />,
document.getElementById('app')
);
第二个文件:
export class StockCount extends React.Component {
render() {
const currentBar = this.props.current;
const totalBar = this.props.total;
const progressBar = currentBar / totalBar * 100;
return (
<div className="container">
<h1>{this.props.current} - {this.props.total} - {this.props.name}</h1>
<div className="progress">
<div className={progressBarType} role="progressbar" aria-valuenow={progressBar} aria-valuemin="0" aria-valuemax="100" style={style}>
<span className="sr-only">{progressBar}% Complete (success)</span>
</div>
</div>
</div>
);
}
答案 0 :(得分:0)
使用生命周期方法进行更新?比如componentWillReceiveProps()https://reactjs.org/docs/react-component.html
答案 1 :(得分:0)
您必须实现服务器推送(将需要服务器更改)才能通知客户端应用程序有关数据库更改的信息。这是最简单的方法,无需修改服务器短拉:
componentDidMount() {
this.lookupInterval = setInterval(() => {
axios
.get('http://reactlaravel.dev/container/count')
.then(function(response) {
this.setState({
containers: response.data,
})
})
}, 500)
}
componentWillUnMount() {
clearInterval(this.lookupInterval)
}