【问题标题】:object can't get method or property 'getCars'对象无法获取方法或属性“getCars”
【发布时间】:2025-12-09 15:25:01
【问题描述】:

我正在研究 react-redux intermidiate..但我不知道出了什么问题 在这个项目上

我已经创建了用于获取汽车详细信息的搜索栏..并且该文件被创建为“search.js”...您可以在此处查看..

search.js

    import React, { Component } from 'react';
    import { connect } from 'react-redux';
    import { getCars } from '../actions';
    import { bindActionCreators } from 'redux';

    class Search extends Component{
        constructor(props){
          super(props);

          this.state = {
            keyword:''
          }
        }

      searchCars = (event) => {
        event.preventDefault();
        this.props.getCars(this.state.keyword)
      }

      handleChange = (event) => {
          this.setState({
            keyword:event.target.value
          })
      }

      componentDidMount(){
        console.log(this.state);
      }

      render(){
        return(
          <div className="main_search">
            <form onSubmit={this.searchCars}>
                <input type="text" value={this.state.keyword} onChange = {this.handleChange} />
            </form>
          </div>
        )
      }
    }

    // mapStateToProps
    // mapDispatchToProps

    function mapDispatchToProps(dispatch){
      return bindActionCreators({getCars}, dispatch)
    }

    export default connect(null,mapDispatchToProps)(Search);

我认为关于 getCars 的错误来自这里。下面将其描述为 s 'index.js'...你可以在这里看到

index.js

    const URL_ROOT = 'http://localhost:3004'

    export default function getCars(keywords){
        const request = fetch(`${URL_ROOT}/carsIndex?q=${keywords}`,
          {method:'GET'})
        .then(response => response.json())

        return{
          type:'SEARCH_CARS',
          payload:request
        }
    }

并且错误看起来像这样..

bundle.js 文件中显示错误

所以尝试修复它并帮助我...

【问题讨论】:

  • 检查 import { getCars } from '../actions';这个路径是否正确

标签: javascript reactjs redux react-router react-redux


【解决方案1】:

请将您的 mapDispatchToProps 方法更改为

    const mapDispatchToProps = (dispatch)=> (
    bindActionCreators(getCars, dispatch) 
)

【讨论】:

  • @mrpanchal 请通过导出函数 getCars(keywords) 而不是默认导出进行检查
  • @mrpanchal 您也将您的操作导出为 import { getCars } from '../actions';但你已经把它写在 index.js 文件中
  • 我已经把我的文件放在了github上。你可以破解它并在codesandbox上导入它...我不熟悉它
  • 在 github 上搜索 mrpanchal
最近更新 更多