首页 > 解决方案 > 价值未发送

问题描述

我是redux的新手。我输入了一段简单的代码,它只发送了“Mike”这个名字

但是,当我单击buttonClick()我创建的函数时.. 也没有发送任何内容,我不确定如何显示发送的值“Mike”,上面写着“嗨,我的名字是...”

下面是我的代码。任何帮助将非常感激

import React from 'react';
import './App.css';
import {changeName} from './reducers.js'
import {createStore} from 'redux';
import {changeNameAction} from './actions'
import {connect} from 'react-redux';

var store = createStore(changeName);

const App = ({buttonClick=f=>f }) => {
      return(
      <div className="App">
        <div> Hi my name is {}  </div>
        <div><button onClick={()=> buttonClick("Mike")}>Change name</button></div>
      </div>
    )
};

const mapStateProps = (state) => {
    return {
        name: state.name
    }
}

const mapDispatchToProps = dispatch => {
    return {
        buttonClick(name){
            dispatch(changeNameAction(name))
        }
    }
}

const Container = connect(mapStateProps,mapDispatchToProps)(App);
export default Container;

标签: reactjsredux

解决方案


我现在无法测试你的代码,但你可以试试这个:

// The connected props are part of the arguments
const App = ({ buttonClick = () => {}, name = '' }) => {
    return(
      <div className="App">
        {/* This way you can render the name prop */}
        <div> Hi my name is {name}</div>
        {/* Execute the function instead of returnning it */}
        <div><button onClick={() => { buttonClick("Mike"); }}>Change name</button></div>
      </div>
    )
};

const mapStateProps = (state) => {
    return {
        name: state.name
    }
}

const mapDispatchToProps = dispatch => {
    return {
        // Key value pair
        buttonClick: (name) => {
            dispatch(changeNameAction(name))
        }
    }
}

希望能帮助到你


推荐阅读