项目中的此类错误:
http://i.piccy.info/i9/c4a98861f1b018f194dd1524bbc6947b/1570286036/32303/1334636/error.jpg
这是我项目主要文件的代码:
CarsList.js:
import React from 'react';
import Car from './Car';
class CarsList extends React.Component {
constructor() {
super();
this.state = {
search: ""
};
}
updateSearch(event) {
this.setState({search:event.target.value.substr(0,100)})
}
render(){
let filterCars = this.props.attributeCarsList.filter(
(contact) => {
return contact.name.toLowerCase().indexOf(this.state.search.toLowerCase()) !== -1;
}
);
return (
<div>
<input type="text" value={this.state.search} onChange={this.updateSearch.bind(this)}/>
{filterCars.map((argumentMap)=>{
return <Car attributeCar={argumentMap}/>
})}
</div>
);
}
}
export default CarsList;
Home.js:
import React from "react";
import {BrowserRouter, Route, Link} from "react-router-dom";
import '../App.css';
import CarsList from "./CarsList.js";
let carsArray = [
{
id:1,
name: 'BMW',
phone: '555 555 5555'
},
{
id:2,
name: 'Mercedes',
phone: '555 111 5555'
},
{
id:3,
name: 'Audi',
phone: '555 777 5555'
},
{
id:4,
name: 'Ford',
phone: '555 888 5555'
}
]
class Home extends React.Component {
render(){
return (
<CarsList attributeCarsList={this.props.attributeApp}/>
);
}
}
export default Home;
export {carsArray};
App.js:
import React from "react";
import ReactDOM from 'react-dom';
import {BrowserRouter, Route, Link, Switch} from "react-router-dom";
import createBrowserHistory from "history/createBrowserHistory";
import './App.css';
import Header from "./smallComponents/Header.js";
import Footer from "./smallComponents/Footer.js";
import Home from "./pageComponents/Home.js";
import About from "./pageComponents/About.js";
import Contacts from "./pageComponents/Contacts.js";
import {carsArray} from "./pageComponents/Home.js";
const history = createBrowserHistory();
class App extends React.Component {
render(){
return (
<BrowserRouter history={history}>
<div className="wrapper">
<Header/>
<Home attributeApp={carsArray} />
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/contacts" component={Contacts} />
</Switch>
<Footer/>
</div>
</BrowserRouter>
)
}
}
export default App;
我很抱歉我不是在沙箱中而是在这里写这三个文件,但是由于某些原因沙箱不支持react路由器,所以我不得不在这里写
答案 0 :(得分:0)
在初始渲染时,道具attributeCarsList
尚未定义,因此在其上调用.filter()
会导致错误。您需要等待组件安装。
此图显示了React中组件的生命周期,这对初学者很有帮助。 http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/
如您所见,在render()
中调用过滤器函数的方式存在问题。太早了。您需要等待componentDidMount
。我将让您通过练习找出实现细节,这很简单。
祝你好运!