mat*_*ilk 5 javascript ajax lifecycle reactjs
所以我有一个有趣的案例,即使用与Ajax调用的反应.
把它放在上下文中,我有一个带有3个标签的手风琴.初始化Accordion react组件后,我首先打开第一个标签,其余标签关闭.每个标签都有它的主体所谓的DictionaryCall组件,如下所示:
return class DictionaryCall extends React.Component {
constructor (props) {
super();
this.state = {
word: '',
data: [],
error: false,
nodata: false,
initialLoaded: props.load
}
}
componentDidMount () {
if(this.state.initialLoaded){
this.callAjax();
}
}
componentWillReceiveProps (nextProps) {
if(nextProps.load){
this.setState({initialLoaded: true});
this.callAjax();
}
}
callAjax () {
$.ajax({
url: this.props.url,
dataType: 'json',
catche: false,
method: 'POST',
data: {word: this.props.word},
success: function(data){
if(!data.length){
this.setState({nodata: true});
} else {
this.setState({data: data});
}
}.bind(this),
error: function(xhr, status, error){
console.log(this.props.url, status, error.toString());
this.setState({error: true});
}.bind(this)
});
}
render () {
let body,
error = this.state.error;
if(this.state.nodata){
body = <div>No definition found</div>
} else {
body = <DataTab data={this.state.data} title={this.props.word}/>
}
return (
<div className="dictionary-call">
{body}
{error ? <ServerError onClick={this.callAjax.bind(this)}/> : null}
</div>
)
}
};
Run Code Online (Sandbox Code Playgroud)
根据React docs设置初始状态与props 的所有拳头都是反模式,直到你明确指定它仅用于组件初始化.
因此,在构造函数中可以看到,我正在设置initialLoaded状态props.load.我传递props.load的true只是第一手风琴选项卡,我想它最初装载.
componentDidMount调用方法并检查initialLoaded状态.如果设置为true它,只需调用ajax并重新渲染组件.
现在是棘手的一点.该componentWillReceiveProps方法.我期待,nextProps.load当用户点击Accordion选项卡打开它时,该组件将会收到.然后props.load传递给具有true值的组件.
我的问题是,是componentWillReceiveProps个好地方this.callAjax()吗?initalLoaded在这种情况下创建状态似乎有点无意义.我不应该简单地依靠props.load而打电话shouldComponentUpdate吗?
或许我应该坚持使用initalLoaded状态和使用componentWillUpdate或componentDidUpdate.
请记住,当手风琴选项卡第一次打开时,我只想调用一次ajax调用.
谢谢!
经过一些研究后,我想回答我自己的问题.希望它可以帮助某人.
解决方案非常简单和干净(在我看来).
componentDidMount () {
if(this.state.initialLoaded){
this.callAjax();
}
}
componentWillReceiveProps (nextProps) {
if(nextProps.load){
this.setState({initialLoaded: true});
}
}
componentWillUpdate (nextProps, nextState) {
if(this.state.initialLoaded !== nextState.initialLoaded) {
this.callAjax();
}
}
Run Code Online (Sandbox Code Playgroud)
此代码适用于组件的所有实例,无论它是第一个手风琴选项卡(最初打开)还是其余选项卡(最初关闭)的子级.
在componentDidMount方法中,我正在检查组件是否应该进行Ajax调用.如果在初始化期间将状态this.props.open设置this.state.initialLoaded为true,则进行ajax调用.否则当然不是.
现在,当用户单击其他选项卡时,该组件正在使用道具componentWillReceiveProps.这里我只是设置状态才nextProps.load为真,因为我想只在load字段为真时加载数据.
最后,如果条件componentWillReceiveProps已满足,我正在检查是否this.state.initialLoaded已更改.因为它只有在nextProp.load为真时才能更改,它会阻止多次调用Ajax请求(当状态从true变为false时).
这样,我只在第一次打开选项卡或最初打开选项卡时调用Ajax请求.
那很简单!
| 归档时间: |
|
| 查看次数: |
2436 次 |
| 最近记录: |