react-redux基本使用

Posted усил

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了react-redux基本使用相关的知识,希望对你有一定的参考价值。

创建 store

import  createStore  from 'redux';
const defaultState = 
    language: 'zh',
    languageList: [
         name: '中文', code: 'zh' ,
         name: '英文', code: 'en' 
    ]


const reducer = (state = defaultState, action) => 
    switch (action.type) 
        case "change_labguage":
            return  ...state, language: action.payload ;
        default:
            return state
    


const store = createStore(reducer);
export default store;

入口文件导入 store

import store from 'redux/index';
import ReactDOM from 'react-dom';
import  Provider  from 'react-redux'
ReactDOM.render(
    <Provider  store=store>
        <App />
    </Provider>,
    document.getElementById('root')
)

在类组件中使用

import  connect  from 'react-redux';
// 将 store 中的数据注入到 props 
const mapStateTopProps = (state) => 
    return 
        language: state.language,
        languageList: state.languageList
    

// 将 dispatch 导入到 props
const mapDispatchToProps = (dispatch) 
    return 
        changeLanguage: (code) => 
            const action = 
                type: "change_language",
                payload: code
            
            dispatch(action);
        
    


class HeaderComponent extends React.Component 

    menuClickHander = (e) => 
        this.props.changeLanguage(e.key);
    

    render() 
        return (
            <div className="header">
                <Dropdown.Button
                    overlay=
                        <Menu onClick=() => this.menuClickHander items=this.props.languageList.map(l =>  return  key: l.code, label: l.name  ) />
                    >this.props.language === 'zh' ? '中文' : 'English'</Dropdown.Button>
            </div>
        )
    

export const HeaderClass = connect(mapStateTopProps, mapDispatchToProps)(HeaderComponent);

在函数组件中使用

import  useSelector, useDispatch  from 'react-redux';
const HeaderFC = () => 
    // 获取 store 数据
    const language = useSelector(state => state.language);
    const languageList = useSelector(state => state.languageList);

    const dispatch = useDispatch();

    const menuClickHander = (e) => 
        const action = 
            type: 'change_labguage',
            payload: e.key
        
        dispatch(action);
    

    return (
        <div className="header">
            <Dropdown.Button
                overlay= <Menu 
                            onClick=() => this.menuClickHander 
                            items=languageList.map(l =>  return  key: l.code, label: l.name  ) />
                >language === 'zh' ? '中文' : 'English'
                </Dropdown.Button>
        </div>
    )

 export default HeaderFC;

以上是关于react-redux基本使用的主要内容,如果未能解决你的问题,请参考以下文章

webpack基本使用

webpack基本使用

webpack基本使用

webpack的基本使用

sh 笔记:配合Vue.js配置Webpack -8。 Webpack最基本的打包命令使用`webpack`

webpack34的基本的使用方法