簡體   English   中英

單擊標記選擇中的 1 個選項並導航到 React Js 中的另一個屏幕時,如何更新狀態

[英]How to update the state when 1 option in tag select is clicked and navigte to another screen in React Js

遇到這個問題,我只能導航到另一個屏幕,但我無法更新標簽選擇的狀態。

//Here is the code I handle to navigate when I click on 1 option.

const onChangeNav=(e)=>{ props.history.push (`/${e.target.value}`) }


//Here is my list of option

 <select className="select" onChange={onChangeNav}>
    <option value="Expression"> 
         Expression 
    </option>
    <option value="editing">
         Editing 
    </option>
    <option value="exceeded">
         When Exceeded 
    </option>
    <option value="tracking" >
         Tracking
    </option>
</select>


所以我點擊其中的 1 個。 例如,當我單擊Editing 時,我將導航到Editing屏幕,然后選擇中的將顯示"Editing" 謝謝大家!

要顯示當前選定的值,需要在狀態中保持該值。

const Dropdown = (props) => {
    const [selected,setSelected] = useState('');
    
   useEffect(()=> {
       if(selected) {
           // you can use a setTimeout here to delay the redirection
           props.history.push (`/${selected}`)
        }
   },[selected])

    function onChangeNav(){ 
        setSelected(e.target.value);
        
    }

    return (
        <select className="select" onChange={onChangeNav} selected={selected}>
            <option value="Expression">Expression</option>
            <option value="editing">Editing</option>
            <option value="exceeded">When Exceeded</option>
            <option value="tracking">Tracking</option>
        </select>
    );
}

這將確保您在重定向到新頁面之前在下拉列表中選擇了一個值。

暫無
暫無

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

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