未定义“状态”

时间:2020-09-06 20:52:44

标签: javascript reactjs

我真的很陌生,但是我只想为我在“输入”栏中输入的每个状态呈现“学院”组件。我收到上述错误。我对渲染部分的过滤是否错误?感谢您帮助新手:)

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;

1 个答案:

答案 0 :(得分:3)

使用类时,您有一个对象state,显然colleagues会在其中。

但是,当您使用useState挂钩时,colleagues本身就是状态属性,setColleagues是它的设置器(setState),您无需编写state.colleagues,只需使用{{1} }。

因此,您需要使用colleagues。但是您在过滤方面也有问题。应该是这样的。 {renderColleges(colleges.filter(search))}