如何将ReactJS应用程序与Wagtail API集成.要遵循的步骤



我正在ReactJS中尝试编写应用程序,后端将使用Wagtail API。我正试图找出在前端和后端需要完成哪些步骤/所有配置才能将ReactJS与Wagtail集成?

使用哪个后端并不重要。您只需要从React中的API调用服务。

小示例:

文件index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from "./App";
export class ReactApp {
static renderService(props, element) {
ReactDOM.render(<App {...props}/>, element);
}
}
window.ReactApp = ReactApp;

文件App.js

import React from 'react';
class App extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
data: null,
inProgress: false
}
}
async fetchData(url) {
return await fetch(url)
.then((response) => response.json())
.then(data => this.setState({data}))
.finally((e) => {
this.setState({inProgress: false})
});
}
componentDidMount() {
this.fetchData(this.props.url);
}

render() {
const {data, inProgress} = this.state;
return (
<div className="app">
{
!inProgress && data &&
(
<div className="app__list">
{
data.map(item => <span className="app__list-item">{item.title}</span>)
}
</div>
)
}
</div>
);
}
}
export default App;

然后用带有index.js入口点的webpack构建js代码,并在html 中调用它

<div id="app"></div>
<script  type="text/javascript" src="build.js"></script>
<script>
ReactApp. renderService({url: 'https://yourApiUrl'}, document.getElementById('app'));
</script>

最新更新