React+axios实现数据获取并渲染

it2026-03-06  3

在网页中通过<script>标签直接使用axios,需要添加标签:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

其他具体axios用法,见官方文档:axios中文文档|axios中文网

 

Demo1:(刚打开页面时获取数据并将其渲染到指定位置,这里使用的GET方式)

关键点:

1)使用react中的类组件

2)在类组件中通过componentDidMount(){}获取需要的数据(官方推荐方法,至于其他函数为什么不好,有说明:React数据获取为什么一定要在componentDidMount里面调用?)

3)原理:通过axios获取数据,在前端取到数据后,通过setState来改变组件状态(可以把获取到的数据直接赋给状态),组件状态改变就会触发react进行新的渲染,从而可以实现在指定位置显示获取到的数据

 

Demo2:(通过点击事件获取后台数据,这里使用的POST方式)

关键点:

1)前端传送数据时的格式需要注意

2)前端获取到数据后逐个读取时的格式需要注意

 

代码:

前端(react+axios):(含Demo1和Demo2)

<script src="https://unpkg.com/react@16/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> <script type="text/babel"> function TT(){ //Demo2部分关键代码 const temp = this; var params = new URLSearchParams(); params.append('name','Fred'); params.append('age','18'); const click = () => { axios.post('/source/plugin/fr_ticket/support.inc.php',params) //这里是后端接口,注意不要跨域 .then(function(response) { console.log(response); alert(response.data.data['age']); }) .catch(function(error) { console.log(error); }) } return ( <div> <span onClick={{click}}>点击发送</span> </div> ); } function DD(props){ //Demo1部分关键代码 return ( <div> <span>姓名: {props.name}</span> <span>年龄:{props.age}</span> </div> ); } class YY extends React.Component { //Demo1部分关键代码 constructor(props){ super(props); this.state = {user:null,age:null} } componentDidMount(){ const _this = this; axios.get('/source/plugin/fr_ticket/siri.php',{}) //这里是后端接口,注意不要跨域 .then(function(response){ _this.setState({user:response.data.data.name,age:response.data.data.age}) }) .catch(function(error){ console.log(error); }) } render() { return ( <div> <DD name={this.state.user} age={this.state.age} /> <TT /> </div> ) } } ReactDOM.render( <YY />, document.getElementById('root') ); </script> <div id="root"></div>

Demo1后端(php):

<?php $name="Fred"; $age=18; $result = array("success" => 1, "code" => 101, "data" => array("name" => $name, "age" => $age)); echo(json_encode($result)); ?>

Demo2后端(php):

<?php $name = $_POST['name']; $age = $_POST['age']; $result = array("success" => 1, "code" => 101, "data" => array("name" => $name, "age" => $age)); echo(json_encode($result)); ?>

 

最新回复(0)