react-redux筆記
阿新 • • 發佈:2020-11-04
參考地址:https://blog.csdn.net/q1056843325/article/details/54880804
使用:
(一)、首頁js引入react-redux和store
import React from 'react'; import ReactDOM from 'react-dom'; import TodoList from "./TodoList"; import { Provider } from 'react-redux' import store from './store' const App = ( // Provider元件接受store做為props,子元件可以通過mapStateToProps方法裡的state獲取到stroe值<Provider store={store}> <TodoList/> </Provider> ) ReactDOM.render( App, document.getElementById('root') );
(二)、配置stroe store/index.js
import { createStore } from 'redux' import reducer from './reducer' const store = createStore(reducer); export default store;
(三)、TodoList.js
import React, { Component } from "react"; import { connect } from "react-redux"; class TodoList extends Component { render() { return ( <div> <div> <input value={this.props.inputValue} onChange={this.props.changeInputValue}/> <button>提交</button> </div> <ul> <li>測試1</li> </ul> </div> ) } }// 負責將通過state獲得的資料對映到展示元件的this.props const mapStateToProps = (state) => { return { inputValue: state.inputValue } } // store.dispatch // 負責將使用者操作轉化為Action的功能函式對映到展示元件的this.props const mapDispatchToProps = (dispatch) => { return { changeInputValue(e) { const action = { type: 'change_input_value', value: e.target.value } dispatch(action); } } } // connect的意思就是連線展示元件與容器元件 export default connect(mapStateToProps, mapDispatchToProps)(TodoList);
(四)、reducer.js
const defaultState = { inputValue: 'hello wprld', list: [] } // 處理action,返回新資料 export default (state = defaultState, action) => { if (action.type === 'change_input_value') { const newState = JSON.parse(JSON.stringify(state)); newState.inputValue = action.value; return newState; } return state; }