create-react-appとmobxの実践
2538 ワード
sudo create-react-app react-mobx-app
cd react-mobx-app && yarn eject
mobx
及びmobx-react
yarn add mobx mobx-react
decorator
yarn add @babel/plugin-proposal-decorators -D
# package.json babel
{
"plugins": [
["@babel/plugin-proposal-decorators", { "legacy": true }],
["@babel/plugin-proposal-class-properties", { "loose" : true }]
]
}
mobx
store src/stores
フォルダ作成src/stores/TodoList.js
ファイルimport { observable, action, computed } from 'mobx'
class TodoList {
@observable list = [1, 2, 3]
//
@action addList = item => {
this.list.push(item)
}
//
@action remove = idx => {
this.list.splice(idx, 1)
}
// list.size
@computed
get todoSize() {
return this.list.length
}
}
const store = new TodoList()
export default store
App
接続store
// src/index.js store app
import { Provider } from 'mobx-react'
import TodoList from './stores/TodoList'
const Root = () => (
)
ReactDOM.render(, document.getElementById('root'))
// view .jsx store
import React from 'react'
import { observer, inject } from 'mobx-react'
@inject('TodoList') // connect
@observer //
class TodoView extends React.Component {
render() {
console.log(this.props.TodoList)
// TodoList {addList: f, remove: f,todoSize:3 ,list: proxy}
return (
{this.props.TodoList.list.map((v, k) => (
{v}
))}
this.props.TodoList.addList()}>
{this.props.TodoList.todoSize}
)
}
}
export default TodoView
// /src/store/TodoList.js
@action
reqList = async ()=>{
fetch('/weather/common?source=xw&weather_type=forecast_1h|forecast_24h|index|alarm|limit|tips&province=%E5%9B%9B%E5%B7%9D&city=%E6%88%90%E9%83%BD')
.then(res=>res.json())
.then(res=>{
console.log(res)
this.list = _.reverse(this.list)
})
}
// view
this.props.TodoList.reqList()}>