Riy*_*ria 10 javascript reactjs
如何在ReactJS中重新加载当前页面?在javascript的情况下,我们可以写window.location.reload();
如何在reactjs中做同样的事情?我可以通过UI添加新数据.但是没有刷新我就无法看清单.我希望每当我添加一些时间本身的数据时.
onAddBucket() {
let self = this;
let getToken = localStorage.getItem('myToken');
var apiBaseUrl = "...";
let input = {
"name" : this.state.fields["bucket_name"]
}
axios.defaults.headers.common['Authorization'] = getToken;
axios.post(apiBaseUrl+'...',input)
.then(function (response) {
if(response.data.status == 200){
let result = self.state.buckets.concat(response.data.buckets)
}else{
alert(response.data.message);
}
})
.catch(function (error) {
console.log(error);
});
}
Run Code Online (Sandbox Code Playgroud)
Nis*_*Edu 16
使用这个可能会有所帮助
window.location.reload();
Run Code Online (Sandbox Code Playgroud)
小智 11
由于 React 最终归结为普通的旧 JavaScript,因此您真的可以将它放在任何地方!例如,您可以将它放在 React 类中的 `componentDidMount()' 函数中。
对于您的编辑,您可能想尝试这样的事情:
class Component extends React.Component {
constructor(props) {
super(props);
this.onAddBucket = this.onAddBucket.bind(this);
}
componentWillMount() {
this.setState({
buckets: {},
})
}
componentDidMount() {
this.onAddBucket();
}
onAddBucket() {
let self = this;
let getToken = localStorage.getItem('myToken');
var apiBaseUrl = "...";
let input = {
"name" : this.state.fields["bucket_name"]
}
axios.defaults.headers.common['Authorization'] = getToken;
axios.post(apiBaseUrl+'...',input)
.then(function (response) {
if (response.data.status == 200) {
this.setState({
buckets: this.state.buckets.concat(response.data.buckets),
});
} else {
alert(response.data.message);
}
})
.catch(function (error) {
console.log(error);
});
}
render() {
return (
{this.state.bucket}
);
}
}
Run Code Online (Sandbox Code Playgroud)
您可以window.location.reload();在componentDidMount()生命周期方法中使用.如果您正在使用react-router,它有一个刷新方法来做到这一点.
编辑:如果您想在数据更新后执行此操作,您可能希望re-render不是a reload,您可以使用this.setState()来执行此操作.这是一个基本的例子,用于触发re-render提取数据.
import React from 'react'
const ROOT_URL = 'https://jsonplaceholder.typicode.com';
const url = `${ROOT_URL}/users`;
class MyComponent extends React.Component {
state = {
users: null
}
componentDidMount() {
fetch(url)
.then(response => response.json())
.then(users => this.setState({users: users}));
}
render() {
const {users} = this.state;
if (users) {
return (
<ul>
{users.map(user => <li>{user.name}</li>)}
</ul>
)
} else {
return (<h1>Loading ...</h1>)
}
}
}
export default MyComponent;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
45403 次 |
| 最近记录: |