首页 > 代码库 > redux

redux

1.声明action常量
 
export const INCREASE = ‘INCREASE‘
 
export const GETSUCCESS = ‘GETSUCCESS‘
 
2.初始化state数据
 
const initialState = {
    number: 1,
    lists: [
        {
            text: ‘ww整个应用的 state 被储存在一棵 object tree 中,并且这个 object tree 只存在于唯一一个 store 中。‘
        },
    ],
    data: []
}
 
3.通过dispatch action进入
 
export
default
function update(state = initialState, action) {
 
    // 根据不同的action type进行state的更新
    switch (action.type) {
    case INCREASE:
        return Object.assign({}, state, {
            number: state.number + action.amount
        })
        break
    case GETSUCCESS:
        return Object.assign({}, state, {
            data: action.json
        })
    default:
        return state
    }
}
 
4.返回一个action对象
export const increase = n = > {
    return {
        type: INCREASE,
        amount: n
    }
}
 
export const getSuccess = (json) = > {
    return {
        type: GETSUCCESS,
        json
    }
}
 
function fetchPosts() {
    return dispatch = > {
        return fetch(‘data.json‘)
            .then((res) = > {
            console.log(res.status);
            return res.json()
        })
            .then((data) = > {
            dispatch(getSuccess(data))
        })
            .
        catch ((e) = > {
            console.log(e.message)
        })
    }
}
 
// 这里的方法返回一个函数进行异步操作
export
function fetchPostsIfNeeded() {
 
    // 注意这个函数也接收了 getState() 方法
    // 它让你选择接下来 dispatch 什么
    return (dispatch, getState) = > {
        return dispatch(fetchPosts())
    }
}
 
5.
 
const getList = state = > {
    return {
        lists//页面中数据: state.update.data//更新到state里的
    }
}
 
export
default connect(
    getList, {
    fetchPostsIfNeeded, refreshData
})(Bar)
 
6.
 
render( < Provider store = {
    store
} > < div > < Router history = {
    history
}
routes = {
    routes
}
/>
<DevTools / > < /div>
</Provider > ,
    document.getElementById(‘mount‘))

  

redux