因此,我正在尝试将Wordpress作为后端,并将React作为前端。 我想在首页上显示一列页面和帖子。 当我单击页面并发布链接时,它将带我到单个页面或发布。
我一次只能执行一个axios请求,似乎如果我使用axios添加另一个get请求,它会抛出“ post.title未定义。”
My Pages.js
import React, { Component } from "react";
import axios from "axios";
class Pages extends Component {
constructor(props) {
super(props);
this.state = {
page: {},
};
this.createMarkup = this.createMarkup.bind();
}
componentDidMount() {
const slug = this.props.match.params.slug;
axios
.get(`http://localhost:8888/WP_Weact/wp-json/wp/v2/pages?slug=${slug}`)
.then(page => {
this.setState({
page: page.data[0]
});
});
}
createMarkup(html) {
return { __html: html };
}
render() {
let build;
if(this.state.page.title) {
build = (
<div>
<h1>{this.state.page.title.rendered}</h1>
<div dangerouslySetInnerHTML={this.createMarkup( this.state.page.content.rendered )} />
</div>
);
} else {
build = <div/>;
}
return build;
}
}
export default Pages;
My Post.js
import React, { Component } from "react";
import axios from "axios";
class PostView extends Component {
constructor(props) {
super(props);
this.state = {
post: {},
};
this.createMarkup = this.createMarkup.bind();
}
componentDidMount() {
const slug = this.props.match.params.slug;
axios
.get(`http://localhost:8888/WP_Weact/wp-json/wp/v2/posts?slug=${slug}`)
.then(post => {
this.setState({
post: post.data[0]
});
});
}
createMarkup(html) {
return { __html: html };
}
render() {
let build;
if(this.state.post.title) {
build = (
<div>
<h1>{this.state.post.title.rendered}</h1>
<div dangerouslySetInnerHTML={this.createMarkup( this.state.post.content.rendered )} />
</div>
);
} else {
build = <div/>;
}
return build;
}
}
export default PostView;
app.js
import React from "react";
import ReactDOM from "react-dom";
import Header from "./components/header";
import PostList from "./components/PostList";
//import PostView from "./components/PostView";
import Posts from "./components/Posts";
import Pages from "./components/Pages";
import { BrowserRouter as Router, Route} from 'react-router-dom';
const App = () => (
<Router>
<div>
<Header />
<section className="section container content">
<Route exact path="/" component={PostList} />
<Route path="/:slug" component={Posts} />
<Route path="/:slug" component={Pages} />
</section>
</div>
</Router>
);
ReactDOM.render(<App />, document.getElementById("app"));