使用Redux处理onClick事件

时间:2019-10-12 06:30:43

标签: reactjs redux react-redux

我是redux的新手,所以只是尝试将redux应用于一个非常简单的应用程序。只要单击按钮,它就会切换单词。但是除了动作外,我应该如何调度我的handleClick函数?现在,当我单击按钮时什么也没有发生。

App.js

import React, { Component } from "react";
import { connect } from 'react-redux'; 

import MyButton from "./MyButton";
import { handleClick } from "./actions"; 

import "./styles.css";

class App extends Component {
  handleClick = () => {
    if (this.state.text === "initial text") {
      this.setState({ text: "" });
    } else {
      this.setState({ text: "initial text" });
    }
  }

  render() {
    return (
      <div className="App">
        <MyButton onClick={()=>this.props.handleClick('hi')} />
        <p>{this.props.text}</p>
      </div>
    );
  }
}

const mapStateToProps = state => ({
    text: state.text
})

const mapDispatchToProps = dispatch => ({
  handleClick: () => dispatch(handleClick)
})

export default connect(mapStateToProps, mapDispatchToProps)(App)

MyButton.js

import React, { Component } from "react";

class MyButton extends Component {
  render() {
    return <button onClick={this.props.onClick}>
            Click Me!
            </button>;
  }
}

export default MyButton;

actions.js

export const handleClick = text => ({
  type: "test_action",
  payload: { ...text }
});

reducers.js

export const reducer = (state = {text:'initial_text'}, action) => {
  if(action.type === 'test_action') {
    return Object.assign({}, state, action.payload)
  }
  return state; 
}

index.js

import React from "react";
import ReactDOM from "react-dom";
import { Provider } from 'react-redux'; 
import { createStore } from 'redux'; 

import { reducer } from "./reducers"; 
import App from "./App"; 

import "./styles.css";

const store = createStore(reducer); 

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

2 个答案:

答案 0 :(得分:1)

问题是上述代码中的mapDispatchToProps handleClick道具不接受参数

const mapDispatchToProps = dispatch => ({
  handleClick: (val) => dispatch(handleClick(val)) // update here so that the 'hi' text is passed to the action creator
})

<MyButton onClick={()=>this.props.handleClick('hi')} />

更新

状态未正确更新

return Object.assign({}, state, { text: action.payload }) //pass an object and not just the value

答案 1 :(得分:1)

您应该将参数传递给handleClick函数:

const mapDispatchToProps = dispatch => ({
  handleClick: (text) => dispatch(handleClick(text))
})

或者只是:

const mapDispatchToProps = { handleClick }

您的操作是在对象内部散布字符串,应按原样使用它:

export const handleClick = text => ({
  type: "test_action",
  payload: text
});

然后,化简器将设置整个状态,而不仅仅是text属性。您可以通过拆分然后重新组合化径来避免混淆:

import { combineReducers } from 'redux'

export const text = (state='', action) => {
  if(action.type === 'test_action') {
    return action.payload;
  }
  return state; 
}

export const reducer = combineReducers({
  text
})