猿问

无法在反应功能组件中的道具上设置状态

我一直无法在我不断得到的道具上设置状态


TypeError:props.setState 不是函数


我正在尝试实现搜索功能


const HeroComp = (props) => {

        let  handleSearchSubmit = (e) => {

          props.setState({searchValue: e.target.value});

      }

      return     <div className='heroComp' >

                <form action="" >

   

                <input type="text" placeholder='search cartigory'  onChange={handleSearchSubmit}   />

                 </form>

            </div>

}


export default HeroComp;

当我 console.log(props) 我得到


{searchValue: ""}

searchValue: ""

__proto__: Object

这是父组件


import images from '../data/images'; //the file from which i'm importing images data


class HomePage extends React.Component{

    constructor(){

        super();

        this.state = {

            images,

            searchValue: ''

        

    }

}


    render(){

        const {images , searchValue} = this.state;

        const filteredImage = images.filter(image => image.cartigory.toLowerCase().includes(searchValue));

            return(

                <div >

                    <HeroComp searchValue={ searchValue }  />

                    <GalleryComp filteredImage={filteredImage} />

                </div>

            )

        }


}


export default HomePage;

我知道这应该很容易,但我只是看不到解决方案。


饮歌长啸
浏览 86回答 2
2回答

慕尼黑的夜晚无繁华

这个怎么样?&nbsp; useEffect(() => {&nbsp; &nbsp; // set the current state&nbsp; &nbsp; setSearchValue(props.searchValue)&nbsp; }, [props]);

MYYA

功能组件没有状态,但你可以使用 reactHooks:import React, { useState } from 'react';const HeroComp = (props) => {&nbsp; &nbsp; &nbsp; let [searchValue, setSearchValue] = useState();&nbsp; &nbsp; &nbsp; let&nbsp; handleSearchSubmit = (e) => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; setSearchValue(e.target.value);&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; &nbsp;<div className='heroComp' >&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <form action="" >&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <input type="text" placeholder='search cartigory'&nbsp; onChange={handleSearchSubmit}&nbsp; &nbsp;/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</form>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div>}export default HeroComp;
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答