[React] 實作<select>下拉選單更新資料
7 min readDec 3, 2019
最近突然接手一個網站,而且是React寫的(之前沒碰過),因為大概有JavaScript的經驗,而且也有開發過Angular,想說就是JS而已,就直接針對客戶的需求來做開發了,但下次真要有事前準備,有時候還是會被一些生命週期的問題雷到…!
在幾個需求之中,我覺得下拉選單的實作可以摸到React的5~6成精髓,從中學到props取值和component傳值(1.一層一層傳、2.使用redux最方便,但用多難管理),還有使用setState()會更新render,還有設值時的dispatch,所以我就用這個為例子來做為這次文章的撰寫。
因為內容滿多,所以我只取重要精華,如果說明不足再請不吝指教,謝謝!
開發流程大致如下:
(1)、開發會議成員API → (2)、會議輸入框 → (3)、API取回會議成員 → (4)、更新下拉選單 → (5)、投送訊息
步驟一:開發API
export const get_meeting_infos = (meeting_id, meeting_passwd) => {
return (dispatch) => {
dispatch(get_meeting_infos_pending());
return fetch(https_url + "/get-meeting-infos?MeetingID=" + meeting_id + "&MeetingPassword=" + meeting_passwd, {
method: 'GET',
mode: 'cors',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
secureProtocol: "TLSv1_2_method"
})
.then(response => {
return response.clone().json();
})
.then((jsonData) => {
console.log(jsonData);
dispatch(get_meeting_infos_success(jsonData));
})
.catch(err => {
console.log(err);
dispatch(get_meeting_infos_error());
});
}
}
步驟二:開發網站介面
<div className="meeting_div_container"><div className="meeting_div"><p>會議室</p><div className="txt_meeting_div"><input className="txt_meeting_ac" type="text" placeholder="會議ID"onKeyDown={this.handleKeyDown} value={this.state.meeting_ac} onChange={(event) => {this.setState({meeting_ac: event.target.value});}} /><input className="txt_meeting_pw" type="text" placeholder="會議密碼"onKeyDown={this.handleKeyDown} value={this.state.meeting_pw} onChange={(event) => {this.setState({meeting_pw: event.target.value});}} /><button className="btn_meeting_use" onClick={this.handleUsersSubmit}>尋找會議成員</button></div></div><div className="meeting_users_div"><p>指定投送</p><select name="users" className="select_meeting_user"onChange={this.handleSelected} value={this.props.push_id}>{console.log(this.props.meeting_info)}{this.props.meeting_info.map((e, key) => {return <optionkey={key}value={e.UserID}>{e.DispalyName}</option>;})}</select></div></div>
<div className="send_filename_div">{this.props.selected_filename_info !== null &&<div role="button" className="send_filename_btn"onClick={this.handleSendSelectedFilenameInfo}>投送</div>}</div>
步驟三:根據網站介面,開發API取回會議成員並設置指定成員投送
API取回會議成員
handleUsersSubmit = () => {if (this.state.meeting_ac) {this.props.get_meeting_infos(this.state.meeting_ac, this.state.meeting_pw);}}
指定成員
handleSelected = (e) => {this.props.set_push_user(e.target.value);}
mapStateToProps
步驟四:更新下拉選單會議成員
React 基本更新流程:function → actions → redux
步驟五:選擇成員進行投送
投送的邏輯,並清空資料
參考
補充:
說明一個API接回資料的問題,資料型態一直是Promise,因為這方面經驗不足,所以試過很多方面.text、String()…等都無法成功轉成Json格式,只有在.json()前面加上clone()才能成功。