使用ES6基礎知識來持續更新我的知識庫
阿新 • • 發佈:2019-01-01
1.合理使用物件解構技巧
//這裡表示函式接受一個引數,該引數有一個Home屬性,該Home屬性是一個物件有location和phoneNum兩個子屬性
const sayHello = ({Home:{location,phoneNum}})=>{
console.log("Hello,my location:",location);
console.log("Hello,my phoneNum:",phoneNum);
}
sayHello({Home:{location:"Hangzhou",phoneNum:"18340816452"}});
列印內容如下:
Hello,my location: Hangzhou
Hello,my phoneNum: 18340816452
下面是redux-async-connect庫的一個用法:
@asyncConnect([{
deferred: true,
//promise函式接受一個物件作為引數,該物件的store屬性含有dispatch和getState兩個子屬性
promise:({store:{dispatch,getState}}) =>{
if(!isLoaded(getState())){
return dispatch(loadWidgets());
}
}
}])
注意:在函式內部列印Home屬性將會報錯,因為此處我們只是將我們傳入的Home物件本身進行了屬性解構
2.處理controlled元件
請參考下面的例子:
class Reservation extends React.Component {
constructor(props) {
super(props);
this.state = {
isGoing: true,
numberOfGuests: 2
};
this.handleInputChange = this.handleInputChange.bind(this);
}
handleInputChange(event) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
//這樣雖然我們有了兩個input,但是我們依然將它繫結到了this.state中了
//注意這裡的:this.setState({[name]: value});
}
render() {
return (
<form>
<label>
Is going:
<input
name="isGoing"
type="checkbox"
checked={this.state.isGoing}
onChange={this.handleInputChange} />
</label>
<br />
<label>
Number of guests:
<input
name="numberOfGuests"
type="number"
value={this.state.numberOfGuests}
onChange={this.handleInputChange} />
</label>
</form>
);
}
}
ReactDOM.render(
<Reservation />,
document.getElementById('example')
);