早上好: 我是Jose,我在Reactjs中设计了一个带有json文件中数据源的小组件。我的问题是我的组件没有检测到这个json文件中的更改,并且内容保持静态。
感谢您的帮助
代码是:
import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios'
import './index.css';
class TableUser extends React.Component {
constructor(props) {
super(props);
this.state = {
data: []
};
}
componentDidMount(){
axios
.get('http://myhost/procesos_arbol.json',
)
.then(({ data })=> {
console.log(data);
this.setState({
data: data
});
})
.catch((err)=> {console.log('no recibido')})
}
render() {
const child = this.state.data.map((el) => {
return <div>
<p>key={ el.nid } | Título - { el.title } |
padre - {el.parent}</p>
</div>
});
return <div>
<div>{ child }</div>
</div>;
}
}
ReactDOM.render(
<TableUser />,
document.getElementById('container')
);
答案 0 :(得分:-1)
一种解决方案是创建间隔以从json文件重新获取数据并每n秒更新一次状态。
let data = [{nid: 1, title: 'A'}, {nid: 2, title: 'B'}]
class TableUser extends React.Component {
constructor(props) {
super(props);
this.state = {data: []};
}
componentDidMount(){
let fetchData = () => {
Promise.resolve(data).then(data => {
this.setState({data})
})
}
fetchData()
this.update = setInterval(fetchData, 2000)
}
componentWillUnmount() {
clearInterval(this.update)
}
render() {
const child = this.state.data.map((el) => {
return <div key={el.nid}>
<p>key={ el.nid } | Título - { el.title }</p>
</div>
});
return <div>
<div>
{ child }
<button
onClick={() => {
data.push({nid: 3, title: 'C'})
}}
>Add Data</button>
</div>
</div>;
}
}
ReactDOM.render(
<TableUser />,
document.getElementById('app')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script>
<div id="app"></div>