【附注信息 ----> 关注公众号:CS阿吉,大家一起分享更多的技术文章,聊天技术问题。】
react axios访问本地json文件
解决方法:必须将json文件放到public文件夹下即可访问
(一)使用axios:
//这个算是redux进阶的Demo
import React, { Component } from "react";
import store from "../../store";
import {
getInputChangeValue,
getAddItemAction,
getDeleteItemAction,
initListAction
} from "../../store/actionCreaters";
import ToDoListUI from './ToDoListUI';
class ToDoListUp extends Component {
constructor(props) {
super(props);
this.state = store.getState();
this.handleInputChange = this.handleInputChange.bind(this);
this.handleStoreChange = this.handleStoreChange.bind(this);
this.handleButtonClick = this.handleButtonClick.bind(this);
/**
* 页面上的内容并没有随着store的更新而更新,所以如下操作:
* store发生改变,则subscribe()绑定的函数会自动执行
*/
store.subscribe(this.handleStoreChange);
}
componentDidMount() {
this.axios("http://localhost:3000/mock/list.json").then((res)=>{
const data = res.data;
const action = initListAction(data);
store.dispatch(action);
}).catch(err=>{
console.log(err);
})
}
// input值改变触发action
handleInputChange(e) {
//定义action两种方式,下面是最原始的一种:(1)
// const action = {
// type: CHANGE_INPUT_VALUE,
// value: e.target.value
// };
//下面是改进的方式:(2)
const action = getInputChangeValue(e.target.value);
store.dispatch(action);
console.log(e.target.value);
}
// 重新渲染页面数据
handleStoreChange() {
this.setState(store.getState());
}
// 提交输入内容
handleButtonClick() {
const action = getAddItemAction();
store.dispatch(action);
}
// 点击列表电影名字,会删除电影
handleItemDelete(index) {
const action = getDeleteItemAction(index);
store.dispatch(action);
}
render() {
return (
<ToDoListUI
list={this.state.list}
inputValue={this.state.inputValue}
handleInputChange={this.handleInputChange}
handleButtonClick={this.handleButtonClick}
handleItemDelete={this.handleItemDelete}
/>
);
}
}
export default ToDoListUp;
核心代码
componentDidMount() {
this.axios("http://localhost:3000/mock/list.json").then((res)=>{
const data = res.data;
const action = initListAction(data);
store.dispatch(action);
}).catch(err=>{
console.log(err);
})
}