简体   繁体   中英

'state' is not defined no-undef

I'm really new to react, but I wanted to render the 'College' component only for each state I input in the 'Input' bar. I'm getting the above error. Am I filtering the rendering portion wrong? Thanks for helping a newbie :)

import College from './College';

const Home = (props) => {

  const [colleges, setColleges] = useState([
    {name: 'Princeton', price: 1100.00, img: Princeton, tag: 'princeton'},
    {name: 'Stanford', price: 1100.00, img: Stanford, tag: 'stanford'},
    {name: 'Brown', price: 1100.00, img: Brown, tag: 'brown'},
    {name: 'Columbia', price: 1100.00, img: Columbia, tag: 'columbia'},
    {name: 'Wake', price: 1100.00, img: Wake, tag: 'wake'},
    {name: 'Ross', price: 1100.00, img: Ross, tag: 'ross'},
  ])
   const [search, setSearch] = useState('')
   const renderColleges = (colleges) => (colleges.map(colleges => <College {...colleges} />))

  return (

    <div>

      <Row align="middle" className='title'>
        <Input placeholder="Search for a school" onChange={(e) => setSearch(e.target.value)} value={search}/>
      </Row>

      <Row align="middle" className='container'>
        {renderColleges(state.colleges.filter(search))}
      </Row>

    </div>
  );
}

export default Home;

When you're using classes, you have an object state and colleagues will be in it obviously.

But when you use useState hook, colleagues itself is the state property and setColleagues is its setter (setState), and you need not write state.colleagues , just use colleagues .

So you need to use {renderColleges(colleges.filter(search))} . But you have an issue in filtering too. It should be something like this. {renderColleges(state.colleges.filter(c => c.name.includes(search))}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM