简体   繁体   中英

Unable to setState on props in react functional component

I have been unable to setState on props I keep getting

TypeError: props.setState is not a function

I'm trying to implement a search function

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;

When I console.log(props) I get

{searchValue: ""}
searchValue: ""
__proto__: Object

This is the parent component

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;

I know this should be easy but I just can't see the solution.

How about this?

  useEffect(() => {
    // set the current state
    setSearchValue(props.searchValue)
  }, [props]);

Functional component dont have state, but you can use reactHooks:

import React, { useState } from 'react';

const HeroComp = (props) => {
      let [searchValue, setSearchValue] = useState();

      let  handleSearchSubmit = (e) => {
          setSearchValue(e.target.value);
      }
      return     <div className='heroComp' >
                <form action="" >

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


export default HeroComp;

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