簡體   English   中英

通過父組件的setState更改道具時,子組件中的數據列表選項不會更新

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

父組件使用setState從數據庫中檢索列表更新其狀態。狀態通過setState傳遞給其子組件。 當父狀態更新時,子組件中的數據列表仍為空列表。

父組件:

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>

            )
        }
    }

子組件:

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>
    )
}

哪一部分出了問題?

您的代碼中有錯別字(在您的父數據列表中拼寫為Datalsit_)...話雖如此...這是您的父組件:

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>
    );
  }
}

我不知道為什么你要把list_id prop as the string 'abc'傳遞list_id prop as the string 'abc'但這list_id prop as the string 'abc' ...

這是您的子組件:

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>
  );
}

請注意<option />之前的return值...而且我假設該值可能是一個對象,因此在數據列表中,您將看到[object, Object]它必須是value={each.something} (我不知道怎么辦,因為我看不到來自http://localhost:3001/uni的API的數據結構

再說一次,我不知道為什么要list prop on your input放一個list prop on your input ……但是無論如何,這應該解決它……

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM