[英]How to prevent browser from fetching the same href repeatedly
我是React的大一新生,我想编写一个通过teamId获取团队成员信息的react组件。
反应代码
import React from 'react'; import PropTypes from 'prop-types'; import UserTable from './pm_user_table'; import {Form,Modal,Input,Button} from 'antd'; const FormItem = Form.Item; class PMBody extends React.Component{ constructor(props){ super(props); this.state={ curTeam:this.props.curTeam, memberList:[] } } componentWillMount(){ console.log('component mount'); } componentWillReceiveProps(nextProps){ if(nextProps.curTeam !== this.state.curTeam){ this.setState({curTeam:nextProps.curTeam}); } } render(){ let {getFieldProps} = this.props.form; const teamId = this.state.curTeam; var myFetchOptions={method: 'GET'}; fetch("http://localhost:3001/teamMembers/" +this.state.curTeam,myFetchOptions) .then(response=>response.json()) .then(json => { this.setState({memberList:json}); } ).catch(function(){ console.log("error"); }); let memberList = this.state.memberList; const body = memberList !='' ? <UserTable dataSource={memberList} actions={this.props.actions} /> : '' ; return ( <div> {body} </div> ) } PMBody.PropTypes = { curTeam:PropTypes.string.isRequired, actions: PropTypes.object.isRequired } export default PMBody =Form.create({})(PMBody);
通过chrome devtool中的网络视图,似乎浏览器反复请求相同的url。
那么,为什么要重复获取相同的URL?
您误解了render()
方法的目的。
每当发生任何变化时,React都会调用render()
来更新您的组件。 它必须是纯净的,不应与其他任何东西交互。
您应该将其移动到componentDidMount()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.