【问题标题】:How to bind action creator to component in redux thunk如何将动作创建者绑定到 redux thunk 中的组件
【发布时间】:2020-04-10 07:00:20
【问题描述】:

我正在尝试将我的动作创建者绑定到反应组件。

请在下面找到代码 sn-p:

import { updateCities } from '../../redux/actions/home';

class Home extends React.Component {
  constructor(props) {
    super(props);
    this.updateCities = updateCities.bind(this);
    this.something = 'some value';
  }

  render() {
    const { updateCities, home } = this.props;
    return (
      <div>
        <div>
          <input
            onChange={e => {
              const searchValue = e.target.value;
              updateCities(searchValue);
            }}
          ></input>

我的动作创建者:

export const updateCities = searchValue => async dispatch => {
  console.log(this.something); // **undefined**
} 

为什么结果是未定义的? 请帮忙。

【问题讨论】:

    标签: javascript reactjs redux redux-thunk thunk


    【解决方案1】:

    首先,我假设您使用来自 react-redux 的 connect 连接您的组件,因为我在您发布的代码中看不到这一点。但是,如果您正在记录一个未定义的值,我假设您已连接此组件,但我必须发布此内容以确保。

    import { connect } from 'react-redux'
    import { updateCities } from '../../redux/actions/home';
    
    class Home extends React.Component {
      // Your component
    }
    
    const mapStateToProps = state => ({
      // your mapped state if you have one else put null where mapStateToProps is in your connect function
    })
    
    export default connect(mapStateToProps, {updateCities})(Home);
    

    现在说您没有将 this.something 传递给您的 updateCities 函数。您有以下内容:

    export const updateCities = searchValue => async dispatch => {
      console.log(this.something); 
    } 
    

    当您没有为它分配值并且没有将它传递给函数时,该函数如何知道this.something 是什么。

    如果你想记录某个东西的值,那么你需要将它传递给函数并为其分配一个值,例如:

    export const updateCities = something => async dispatch => {
      console.log(something); 
    } 
    

    在您的组件中,您可以将this.something 传递给您的函数,例如updateCities(this.something)

    现在,如果您要做的是记录 searchValue,然后在 updateCities 函数中记录 searchvalue

    export const updateCities = searchValue => async dispatch => {
      console.log(searchValue);
    } 
    

    【讨论】:

    • 您的示例的问题是我需要更新“某物”,而不仅仅是在动作创建者中使用他。例如:如果我将某物更新为“其他东西”,那么构造函数中的某物属性也应该更新。
    • 您打算如何更新 something 值?您的示例代码非常令人困惑,因为您将 searchValue 传递给 updateCities 函数,但在 updateCities 函数中,您试图控制台记录 this.something 值。您对此代码的计划是什么。是您尝试传递给 updateCities 函数的 searchValue 还是 this.something,如果是 this.something,您打算如何更新此值。
    猜你喜欢
    • 1970-01-01
    • 2019-03-20
    • 1970-01-01
    • 2016-10-18
    • 2021-03-03
    • 1970-01-01
    • 2019-09-22
    • 2020-05-23
    • 2017-02-10
    相关资源
    最近更新 更多