简体   繁体   中英

Datalist options in child component won't update when props are changed through parent component's setState

The parent component updates its state with retrieved list from database using setState .The state is passed to its child component via props. When the parent's state is updated, the datalist in the child component is still empty list.

Parent component:

export default class Major extends Component {
        constructor(props) {
            super(props)
            this.state = {
                uni: []
            }
        }
        componentDidMount() {

            axios.get('http://localhost:3001/uni').then((res) => {
                this.setState({uni: res.data})
            }).catch((e) => {
                console.log('something wrong occured: ' + e)
            })
        }
        render(){
            return (
                <div>
                    <Datalsit_ list={this.state.uni} list_id='abc' />
                </div>

            )
        }
    }

Childe component:

export default function Datalist({list_id, list}){
    return(
        <div>
            <input type="text" list={list_id} />
            <datalist id={list_id} >
            { list.map((each) => {
                <option value={each} />
            })}
            </datalist>
        </div>
    )
}

What part goes wrong?

There are typos in your code (in your parent Datalist is spelled as Datalsit_ )... Having said that... Here is your parent component:

export default class Major extends Component {
  state = { uni: [] };

  componentDidMount() {
    axios
      .get('http://localhost:3001/uni')
      .then(res => {
        this.setState({ uni: res.data });
      })
      .catch(e => {
        console.log('something wrong occured: ' + e);
      });
  }
  render() {
    return (
      <div>
        <DataList list={this.state.uni} list_id="abc" />
      </div>
    );
  }
}

I have no idea why you're passing the list_id prop as the string 'abc' but that's beside the point...

Here is your Child component:

export default function Datalist({ list_id, list }) {
  return (
    <div>
      <input type="text" list={list_id} />
      <datalist id={list_id}>
        {list.map((each, i) => {
          return <option key={i} value={each} />;
        })}
      </datalist>
    </div>
  );
}

Note the return before the <option /> ... And I'm assuming the value is probably an object so in the datalist you're going to see [object, Object] It needs to be value={each.something} (I have no idea what as I can't see the structure of the data coming from the API at http://localhost:3001/uni )

Again, I have no idea why you would put a list prop on your input ... but in any case, this should fix it...

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