所以我似乎打破了React的方式。我目前有一些设置,主App容器(包含所有路由器逻辑)将从API获取其初始状态的所有数据。
我传递了这个功能:
createPage(page) {
console.log('submitted')
instance.post('/admin/createPage',page).then((response) => {
console.log(response)
}).catch((error) => {
console.log(error)
})
}
API接受数据,我看到它更新了数据库。
我的问题是:在我提交数据后,容器组件不会更新它保存所有数据的状态。
例如,这是App容器:
import React, { Component } from 'react';
import {
BrowserRouter as Router,
Route
} from 'react-router-dom'
import axios from 'axios'
import Header from '../components/Header'
import Dashboard from './Dashboard'
import AddEditPage from './AddEditPage'
const instance = axios.create({baseURL: 'http://localhost:1337'})
class App extends Component {
constructor(props) {
super(props);
this.state = {
"pages": []
}
this.createPage = this.createPage.bind(this)
}
componentDidMount() {
this.getPages()
}
getPages() {
instance.get('/admin/listPages')
.then(
(response) => {
this.setState(
{
"pages": response.data
}
)
})
.catch((error) => {console.log(error)})
}
createPage(page) {
console.log('submitted')
instance.post('/admin/createPage',page).then((response) => {
console.log(response)
}).catch((error) => {
console.log(error)
})
}
render() {
return (
<Router>
<div className="Router">
<div className="Navbar">
<Header />
</div>
<div className="Wrapper">
<Route exact path="/" render={ () => (
<Dashboard pages={this.state.pages} />
)} />
<Route path="/admin/new-page" render={ () => (
<AddEditPage createPage={this.createPage} />
)} />
<Route path="/admin/edit-page/:id" render={ () => (
<AddEditPage />
)} />
</div>
</div>
</Router>
);
}
}
export default App;
目前,我通过在提交后设置window.href解决了这个问题。这会重新加载整个页面(不理想)。
handleSubmit(e) {
e.preventDefault();
this.props.createPage(this.state)
//TODO: update main container state of page titles, then redirect
window.location = "/"
}
答案 0 :(得分:2)
componentDidMount
上调用 this.getPages
- 所以在组件最初安装后,您的状态永远不会更新。创建新页面后,您需要再次致电createPage(page) {
console.log('submitted')
instance.post('/admin/createPage',page).then((response) => {
console.log(response);
// after page is created, refetch pages
// this.getPages calls setState and your component will re-render
this.getPages();
}).catch((error) => {
console.log(error);
})
}
:
handleSubmit
或者如果您愿意,可以将其链接到handleSubmit(e) {
e.preventDefault();
this.props.createPage(this.state).then(this.getPages);
}
:
<script type="text/javascript">
var onloadCallback = function() {
grecaptcha.render('html_element', {
'data-theme' : 'dark'
});
};
</script>