我想對每個setState調用的react組件執行狀態驗證,如果新狀態無效,請使用另一個有效狀態。React狀態驗證
舉例來說,如果我有滑塊,用4頁,我想要做的
this.setState({
page: 5
});
在我的驗證功能,我會檢查新狀態的值是否大於頁面數,如果是這樣,我d設置4(總頁數),而不是提供5.
這可能嗎? 謝謝
我想對每個setState調用的react組件執行狀態驗證,如果新狀態無效,請使用另一個有效狀態。React狀態驗證
舉例來說,如果我有滑塊,用4頁,我想要做的
this.setState({
page: 5
});
在我的驗證功能,我會檢查新狀態的值是否大於頁面數,如果是這樣,我d設置4(總頁數),而不是提供5.
這可能嗎? 謝謝
我不知道,但shouldComponentUpdate
方法可以幫助你。
class Example extends React.Component {
constructor(){
super();
this.state={
count: 0
}
this.handleClick = this.handleClick.bind(this);
this.reset = this.reset.bind(this);
}
shouldComponentUpdate(nextProps,nextState){
return nextState.count <= 4
}
handleClick(){
const newState = this.state.count + 1;
this.setState({count: newState})
}
reset(){
this.setState({count: 0});
}
render(){
return <div>
<p>State: {this.state.count}</p>
<button onClick={this.handleClick}>Click Me</button>
<button onClick={this.reset}>Reset</button>
</div>
}
}
React.render(<Example />, document.getElementById('container'));
但它也取決於你的邏輯是否應該更新組件。 fiddle example
我希望它能幫助你。
是的,這當然是可以的。只需打包setState
,以便您可以在執行調用之前進行驗證。喜歡的東西:
function checkThenSet(newState){
// do validation here
if (validation) {
this.setState(newState);
} else {
// validation failed
this.setState(otherState);
}
}
如果您通過用戶交互的方式更新您的狀態,那麼你的渲染功能是這樣的
var MyComponent = React.createClass({
checkThenSet: function(newState) {/* Same as above */},
render: function() {
return (<input
type="text"
value={this.state}
onChange={this.checkThenSet}
/>);
}
});
我想隱式執行驗證。所以即使我在設置之前忘記檢查值,我也希望組件能夠檢查自己的狀態。 –
你看過'shouldComponentUpdate'方法嗎? –
是的,我正在使用它,但它看起來並不像這是正確的用例。 –