1

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

请在下面找到代码片段:

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**
} 

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

4

1 回答 1

0

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

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);
} 
于 2019-12-18T02:32:37.060 回答