简体   繁体   English

redux中如何使用mapDispatchToProps和Reducers?

[英]How to use mapDispatchToProps and Reducers in redux?

this is file app.js这是文件 app.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App'
import {createStore} from 'redux'
import {Provider} from 'react-redux'
import reducers from './reducers'

const store = createStore(reducers)
ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);



this is reducers这是减速机

let defaultState = []
export default function reducer(state = defaultState, action){
   switch(action.type){
       case 'ADD_TODO':
           return {
               defaultState : [...state, action.text] 
           }
       default:
           return state
   }
}

this is file item.js这是文件 item.js

.......
import addTodo from './action'
class Item extends Component {
    constructor(){
        super()
        this.inputRef = createRef()
    }
    render() { 
        return (
        <>
            <input ref = {this.inputRef} type = 'text'></input>
            <button onClick = {() => this.props.add(this.inputRef.current.value)} type= 'button' >Add Todo</button> 
            {this.props.todoList.map(item => <h5>{item}</h5>) } 
            {/* this is error */}
        </>
        );
    }
}

const mapStateToProps = (state) => {
    return {
      todoList : state
    }
}
const mapDispatchToProps = (dispatch) => {
   return {
    add : (text) => dispatch(addTodo(text))
   }
}
export default connect(mapStateToProps,mapDispatchToProps)(Item)

this is file action.js这是文件 action.js

const ADD_TODO = 'ADD_TODO'
 const addToto = (text) => {
    return {
        type : ADD_TODO,
        text
    }
}
export default addToto;

Error: this.props.todoList.map is not a function i want to add new item when i onClick in button addtodo then display on tag h5.错误:this.props.todoList.map 不是 function 当我在按钮 addtodo 中的 onClick 然后显示在标签 h5 上时,我想添加新项目。 and check for me when i get value from tag input, IT's TRUE当我从标签输入中获得价值时检查我,这是真的

Your defaultState is an array and you are returning object in ADD_TODO .您的 defaultState 是一个数组,您将在 ADD_TODO 中返回ADD_TODO

Fix使固定

let defaultState = []
export default function reducer(state = defaultState, action){
   switch(action.type){
       case 'ADD_TODO':
           return [...state, action.text] //<---- see here
       default:
           return state
   }
}

Edit Also you need to use current to access the value of ref编辑您还需要使用current来访问 ref 的值

<button onClick = {() => this.props.add(this.inputRef.current.value)} type= 'button' >Add Todo</button> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM