**尝试运行此代码而代码成功编译时,出现错误“ TypeError:searchField.toLowerCase不是函数”
import React, { Component } from 'react';
import CardList from '../Components/CardList';
import SearchBox from '../Components/SearchBox';
//import { robots } from './robot';
import './App.css';
import Scroll from '../Components/Scroll';
import ErrorBoundry from '../Components/ErrorBoundry';
import { connect } from 'react-redux';
import { searchChange } from '../actions'
const mapStateToProps = state => {
return {searchField:state.searchField}
}
const mapDispatchToProps = (dispatch) =>{
return {
searchField:(event) => dispatch(searchChange(event.target.value))
}
}
class App extends Component {
constructor(){
super()
this.state = {
robots:[]
}
}
componentDidMount() {
fetch('https://jsonplaceholder.typicode.com/users').then(respond =>{
return respond.json()
}).then(users =>{
this.setState({robots:users})
})
}
render(){
const { searchField, onSearchChange } = this.props;
const filterRobots = this.state.robots.filter(robots =>{
//trying to search robot with either upper case or lower case
return robots.name.toLowerCase().includes(searchField.toLowerCase())
});
return(
<div className="tc">
<h1 className="head"> Robo Friend App</h1>
<div>
<SearchBox searchChange={onSearchChange}/>
</div>
<Scroll>
<ErrorBoundry>
<CardList robots={filterRobots} />
</ErrorBoundry>
</Scroll>
</div>
)
}
}
export default connect(mapStateToProps, mapDispatchToProps)(App);
答案 0 :(得分:1)
您的mapDispatchToProps
函数似乎覆盖了searchField
中定义的mapStateToProps
道具。因此searchField
道具实际上是一个函数,而不是字符串。
答案 1 :(得分:0)
从
更改 mapDispatchToProps 代码块
const mapDispatchToProps = (dispatch) =>{
return {
searchField:(event) => dispatch(searchChange(event.target.value))
}
}
进入
const mapDispatchToProps = (dispatch) =>{
return {
onSearchChange:(event) => dispatch(searchChange(event.target.value))
}
}
实现中的问题是,您同时对mapStateToProps和mapDispatchToProps使用相同的(prop)名称,在这种情况下,稍后将覆盖第一个。
答案 2 :(得分:-1)
您的filterRobots
函数尝试在searchField
仍未定义的情况下运行
尝试像这样运行过滤器之前检查searchField
的值
const filterRobots = this.state.robots.filter(robots =>{
//*** add the next line
if(!searchField) return undefined
//trying to search robot with either upper case or lower case
return robots.name.toLowerCase().includes(searchField.toLowerCase())
});
这确保了这一行
return robots.name.toLowerCase().includes(searchField.toLowerCase())
仅在searchField
具有值时运行