Javascript 自动更新包含React中对象的列表

Javascript 自动更新包含React中对象的列表,javascript,arrays,reactjs,lifecycle,Javascript,Arrays,Reactjs,Lifecycle,在向列表中添加新对象时,如何使用对象自动更新列表? 我有您过去的活动列表条目,如照片示例中所示,我需要在每次添加活动时更新它。目前,添加的元素仅在我刷新浏览器页面时显示。我有数据库中的对象。所以当我添加一个元素时,首先它被添加到数据库中 我希望我说得够清楚了,你们能帮我 onClick={this.handleUpdateSubmit} is the function which update the list 这是我的密码 class UserDashboard extends Reac

在向列表中添加新对象时,如何使用对象自动更新列表? 我有您过去的活动列表条目,如照片示例中所示,我需要在每次添加活动时更新它。目前,添加的元素仅在我刷新浏览器页面时显示。我有数据库中的对象。所以当我添加一个元素时,首先它被添加到数据库中

我希望我说得够清楚了,你们能帮我

onClick={this.handleUpdateSubmit} is the function which update the list 
这是我的密码

class UserDashboard extends React.Component {

state = {
    uid: this.props.userDetails.uid,
    page: 1,
    redirect: false,
    target: 15,
    selectedRole: 4,
    selectedSourceRole: 1,
    quote_nr: '',
    source_id: '',
    status_id: '',
    errorMessage: '',
    message: '',
    cost: '',
    rebate: '',
    pageLoading: false,
    date: '2222-01-02',
    therapists:[],
    globalTargets:[],
    follows:[],
    weekly:[],
    utc: new Date().toISOString().slice(0, 19).replace('T', ' '),
}

topProfilesUrl = 'therapists/top/profiles';
getGlobalTargets = 'owner/targets';
followActivities = 'user/follow/activities';
weeklyTarget= 'user/weekly/leads';

componentDidMount = () => {
    const { getActivities,getFollowActivities,getTarget } = this;
    getActivities();
    getFollowActivities();
    getTarget();
    window.scrollTo(0, 0);
}


UNSAFE_componentWillReceiveProps = (newProps) => {
    let apiDat = newProps.apiDat;
    let apiData = newProps.apiData;
    if (this.props.apiData !== newProps.apiData) {
        if (apiData.activities && apiData.activities.success) {
            let therapists = apiData.activities.therapists;
            let hasMore = true;
            console.log("unu")

            if (therapists.length < 10) {
                hasMore = false;
            }

            this.setState(() => ({
                therapists: this.state.therapists.concat(therapists),
                hasMore: hasMore,
                pageLoading: false
            }))
        }
    }
    if (this.props.apiData !== newProps.apiData) {
        if (apiData.leads && apiData.leads.success) {
            let weekly = apiData.leads.weekly;
            let hasMore = true;
            console.log("unu")

            this.setState(() => ({
                weekly: this.state.weekly.concat(weekly),
                hasMore: hasMore,
                pageLoading: false
            }))
        }
    }

    if (this.props.apiDat !== newProps.apiDat) {

        if (apiDat.targets && apiDat.targets.success) {
            console.log("doi")

            let globalTargets = apiDat.targets.globals;
            let hasMore = true;
            if (globalTargets.length < 10) {
                hasMore = false;
            }

            this.setState(() => ({
                globalTargets: this.state.globalTargets.concat(globalTargets),
            }))
        }
    }
    if (this.props.apiData !== newProps.apiData) {
        if (apiData.followActivities && apiData.followActivities.success) {
            console.log("trei")

            let follows = apiData.followActivities.follows;
            let hasMore = true;
            if (follows.length < 10) {
                hasMore = false;
            }

            this.setState(() => ({
                follows: this.state.follows.concat(follows),
            }))
        }
    }
}
getTarget = () => {
    this.setState({pageLoading: true}, () => { this.loadTargets() })
}

loadTargets = () => {
    console.log("load")
    this.props.actions.reqGetGlobalTargets({
        body: {},
        headers: null,
        resource: `${this.getGlobalTargets}?page=${this.state.page}`
    })
}

getFollowActivities= () => {
    this.setState({pageLoading: true}, () => { this.loadFollowActivities() })
}
loadFollowActivities = () => {
    console.log("load")
    this.props.actions.reqGetFollowActivities({
        body: {},
        headers: null,
        resource: `${this.followActivities}?page=${this.state.page}`
    })
}
renderLeads = () => {
    return (
        this.state.globalTargets.slice(0,1).map( (t, idx) => (
            t.daily_leads
        ))
    )
}
renderSales = () => {
    return (
        this.state.globalTargets.slice(0,1).map( (t, idx) => (
            t.daily_sales
        ))
    )
}
renderRatio = () => {
    return (
        this.state.globalTargets.slice(0,1).map( (t, idx) => (
            t.close_ratio
        ))
    )
}
weeklyLeads = () => {
    const nr = this.state.weekly.map( (t, idx) => (
        t.Leads||0
    ))
    return nr;
}
weeklySales = () => {
    const nr = this.state.weekly.map( (t, idx) => (
        t.Sales||0
    ))
    return nr;
}
getActivities = () => {
    this.setState({pageLoading: true}, () => { this.loadActivities() })
}

loadActivities = () => {
    this.props.actions.reqGetTherapistsTopProfiles({
        body: {},
        headers: null,
        resource: `${this.topProfilesUrl}?uid=${this.state.uid}`
    })
}
renderActivities = () => {
    const items = this.state.therapists.map( (t, idx) => (
        <tr key={t.id} className="activity-display-table">
            <td>Quote Nr.: {t.quote_nr}</td>
            <td>Source: {t.source_id}</td>
            <td>Status: {t.status_id}</td>
            <td>Cost: ${t.cost}</td>
            <td>Rebate: ${t.rebate}</td>
            <td>Date: {t.date.slice(0,10).replace(/-/g,'-')}</td>
        </tr>
    ))
    return (
        <div ref={0} className="therapist-list">
            <h2>Your Past Entries: </h2>
            { items }
        </div>
    )
}

renderFollowActivities = () => {
    const items = this.state.follows.map( (t, idx) => (
        <tr key={t.id} className="activity-display-table">
            <td>Quote Nr.: {t.quote_nr}</td>
            <td>Source: {t.source_id}</td>
            <td>Status: {t.status_id}</td>
            <td>Cost: ${t.cost}</td>
            <td>Rebate: ${t.rebate}</td>
            <td>Date: {t.date.slice(0,10).replace(/-/g,'-')}</td>
        </tr>
    ))
    return (

        <div ref={0} className="therapist-list">
            { items }
        </div>

    )
}
getleads = () =>{
    const id = "Lead";
    const dd =  this.state.utc.slice(0,10).replace(/-/g,'-');
    const count = this.state.therapists.filter((t) => t.status_id === id && t.date.slice(0,10).replace(/-/g,'-')===dd).length;
    const nb = this.state.therapists.filter((t) => t.date.slice(0,10).replace(/-/g,'-') === dd).length;

   // console.log(count);
    //console.log(nb);
    //console.log(dd);
    return count;
}

getsales = () =>{
    const status = "Sold";
    const dd =  this.state.utc.slice(0,10).replace(/-/g,'-');
    const nr = this.state.therapists.filter((t) => t.status_id === status && t.date.slice(0,10).replace(/-/g,'-')===dd).length;
 //   const nb = this.state.follows.filter((t) => t.date.slice(0,10).replace(/-/g,'-') === dd).length;
    console.log(nr);
    return nr;
}
submitUrl = 'registerActivities';
updateUrl = 'updateActivities';

handleChange = (eve) => {

    let inputName = eve.target.name,
        value = eve.target.value;

    this.setState(() => {
        return {[inputName]: value}
    })
}

handleSubmit = () => {
    this.setState({errors: []}, () => {

        const formValid = this.validateForm()

        if (!formValid) {
            return;
        }

        const acBody = {
            quote_nr: this.state.quote_nr,
            cost: this.state.cost,
            source_id: this.state.selectedSourceRole,
            status_id: this.state.selectedRole,
            date: this.state.utc,
            rebate: this.state.rebate,
            user_id:this.state.uid,
        }
       this.props.actions.reqActionsUsers(acBody, this.submitUrl);
    })
}

handleUpdateSubmit = () => {
    this.setState({errors: []}, () => {

        const formValid = this.validateForm()

        if (!formValid) {
            return;
        }

        const aBody = {
            id: this.state.id,
            quote_nr: this.state.quote_nr,
            cost: this.state.cost,
            source_id: this.state.selectedSourceRole,
            status_id: this.state.selectedRole,
            date: this.state.utc,
            rebate: this.state.rebate,
            user_id:this.state.uid,
        }
        console.log(aBody);
        this.props.actions.reqUpdateAction(aBody, this.updateUrl);
    })
}

validateForm = () => {

    let formValid = true;

    if (this.state.quote_nr === '') {
        formValid = false;
        this.setState( () => ({
            errors: [
                {input: 'quote_nr'}
            ],
            errorMessage: 'Quote Number is mandatory',
        }))
    } else if (this.state.cost === '') {
        formValid = false;
        this.setState( () => ({
            errors: [
                {input: 'cost'}
            ],
            errorMessage: 'Cost is mandatory'
        }))
    } else if (this.state.rebate === '') {
        formValid = false;
        this.setState( () => ({
            errors: [
                {input: 'rebate'}
            ],
            errorMessage: 'Rebate is mandatory'
        }))
    }
    if (formValid === true) {
        this.setState( () => ({
            message: 'You Activity Has Been Added',
            errorMessage: ''
        }))
    }
    return formValid

}

handleStatusChange = (event) => {
    let statusId = event.target.value;
    this.setState(() => ({
        selectedRole: statusId
    }))
}

handleSourceChange = (ev) => {
    let statusId = ev.target.value;
    this.setState(() => ({
        selectedSourceRole: statusId
    }))
}

render () {
    console.log("weekly",this.weeklyLeads());
    return (

        <MainWrapper>
            <div id="user-dashboard">
                <HeaderUser logoutRedirect="/signin"/>
                <div className="page-background">
                    <SidebarUser page="dashboard"/>
                    {/* Page Content */}
                    <div className="inner-content">
                        <div className="top-row">
                            <h1>Salesperson Dashboard</h1>
                        </div>
                        <div className="second-row">
                        </div>
                        <div className="activity-table">
                            <table className="a">
                                <tr>
                                    <th>Today's Targets ({this.state.utc.slice(0,10).replace(/-/g,'-')})</th>
                                    <th>Weekly Targets</th>
                                    <th>Bonus So Far This Week</th>
                                </tr>
                                <tr>
                                    <td>{this.getleads()}/{this.renderLeads()} Leads Handled</td>
                                    <td>{this.weeklyLeads()}/{this.renderLeads()*5} Leads Handled</td>
                                    <td>$0 From Leads</td>
                                </tr>
                                <tr>
                                    <td>{this.getsales()}/{this.renderSales()} Sales</td>
                                    <td>{this.weeklySales()}/{this.renderSales()*5} Sales</td>
                                    <td>$0 From Sales</td>
                                </tr>
                                <tr>
                                    <td>0/{this.renderRatio()} Close Ratio</td>
                                    <td>0/{this.renderRatio()*5} Close Ratio</td>
                                    <td>$0 From Profit Share</td>
                                </tr>
                            </table>
                        </div>
                        <div>
                           <h2>Leads Due For A Followup</h2>
                            { this.renderFollowActivities() }

                        </div>
                        <h2 className="activity">Add Activity</h2>
                        <div className="activity-menu">
                            <input type="text"
                                   placeholder="Quote Number"
                                   name="quote_nr"
                                   onChange={this.handleChange}
                                 />
                                <select  onChange={this.handleSourceChange}>
                                    <option value="1">Phone</option>
                                    <option value="2">Email</option>
                                    <option value="3">Live Chat</option>
                                </select>
                            <select  onChange={this.handleStatusChange}>
                                <option value="4">Lead</option>
                                <option value="5">Sold</option>
                            </select>
                            <input type="text"
                                   placeholder="Cost"
                                   name="cost"
                                   onChange={this.handleChange}
                            />
                            <input type="text"
                                   placeholder={this.state.cost/20||("Recom. Rebate" + " $")}
                                   name="recRebate"
                                   readOnly
                            />
                            <input type="text"
                                   placeholder={this.state.cost/10||("Max Possible Rebate" + " $")}
                                   name="maxRebate"
                                   readOnly
                            />
                            <input type="text"
                                   placeholder="Final Rebate $"
                                   name="rebate"
                                   onChange={this.handleChange}
                            />
                        </div>
                        <p className="error-message">{this.state.errorMessage}</p>
                        <Popup
                        content={this.state.message}
                        on="click"
                        pinned
                        trigger={

                            <ButtonRoundGradient className="activity_button" text="Add Activity"
                                                 onClick={this.handleSubmit}/>
                        }
                        />
                        <Popup
                            content={"Activity Has Been Updated"}
                            on="click"
                            pinned
                            trigger={
                        <ButtonRoundGradient className="activity_button" text="Update Activity"  onClick={this.handleUpdateSubmit}/>
                            }
                        />
                        { this.renderActivities() }

                    </div>
                </div>
            </div>
        </MainWrapper>
    )
}
类UserDashboard扩展了React.Component{ 状态={ uid:this.props.userDetails.uid, 页码:1, 重定向:false, 目标:15, 选择的角色:4, selectedSourceRole:1, 引用编号:'', 源\u id:“”, 状态\u id:“”, 错误消息:“”, 消息:“”, 成本:'', 回扣:'', 页面加载:false, 日期:“2222-01-02”, 治疗师:[], 全局目标:[], 如下:[], 每周:[], utc:new Date().toISOString().slice(0,19).替换('T',''), } topProfilesUrl=‘治疗师/top/profiles’; getGlobalTargets='所有者/目标'; followActivities='user/follow/activities'; weeklyTarget='用户/每周/潜在客户'; componentDidMount=()=>{ const{getActivities,getFollowActivities,getTarget}=this; getActivities(); getFollowActivities(); getTarget(); 滚动到(0,0); } 不安全组件将接收道具=(新道具)=>{ 设apiDat=newProps.apiDat; 设apiData=newProps.apiData; if(this.props.apiData!==newProps.apiData){ if(apiData.activities&&apiData.activities.success){ 让治疗师=apiData.activities.therapists; 让hasMore=真; 控制台日志(“联合国大学”) if(治疗师,长度<10){ hasMore=假; } 此.setState(()=>({ 治疗师:这个。州。治疗师。康卡特(治疗师), 哈斯莫尔:哈斯莫尔, 页面加载:false })) } } if(this.props.apiData!==newProps.apiData){ if(apiData.leads&&apiData.leads.success){ let weekly=apiData.leads.weekly; 让hasMore=真; 控制台日志(“联合国大学”) 此.setState(()=>({ 每周:本。州。每周。康卡特(每周), 哈斯莫尔:哈斯莫尔, 页面加载:false })) } } if(this.props.apiDat!==newProps.apiDat){ if(apiDat.targets&&apiDat.targets.success){ console.log(“doi”) 设globalTargets=apiDat.targets.globals; 让hasMore=真; 如果(globalTargets.length<10){ hasMore=假; } 此.setState(()=>({ globalTargets:this.state.globalTargets.concat(globalTargets), })) } } if(this.props.apiData!==newProps.apiData){ if(apidat.followActivities&&apidat.followActivities.success){ console.log(“trei”) 让follows=apiData.followActivities.follows; 让hasMore=真; 如果(长度小于10){ hasMore=假; } 此.setState(()=>({ follows:this.state.follows.concat(follows), })) } } } getTarget=()=>{ this.setState({pageLoading:true},()=>{this.loadTargets()}) } loadTargets=()=>{ 控制台日志(“加载”) this.props.actions.reqGetGlobalTargets({ 正文:{}, 标题:null, 资源:`${this.getGlobalTargets}?page=${this.state.page}` }) } getFollowActivities=()=>{ this.setState({pageLoading:true},()=>{this.loadFollowActivities()}) } loadFollowActivities=()=>{ 控制台日志(“加载”) this.props.actions.reqGetFollowActivities({ 正文:{}, 标题:null, 资源:`${this.followActivities}?页面=${this.state.page}` }) } renderLeads=()=>{ 返回( this.state.globalTargets.slice(0,1).map((t,idx)=>( t、 每日销售线索 )) ) } renderSales=()=>{ 返回( this.state.globalTargets.slice(0,1).map((t,idx)=>( t、 每日销售 )) ) } 渲染=()=>{ 返回( this.state.globalTargets.slice(0,1).map((t,idx)=>( t、 闭合比 )) ) } 周刊杂志=()=>{ const nr=此.state.weekly.map((t,idx)=>( t、 导线| | 0 )) 返回nr; } 周刊杂志=()=>{ const nr=此.state.weekly.map((t,idx)=>( t、 销售额| | 0 )) 返回nr; } getActivities=()=>{ this.setState({pageLoading:true},()=>{this.loadActivities()}) } loadActivities=()=>{ this.props.actions.reqGetTherapistsTopProfiles({ 正文:{}, 标题:null, 资源:`${this.topProfilesUrl}?uid=${this.state.uid}` }) } 渲染率=()=>{ const items=this.state.therapists.map((t,idx)=>( 报价编号:{t.Quote\U Nr} 来源:{t.Source_id} 状态:{t.Status\u id} 成本:${t.Cost} 返利:${t.retrieve} 日期:{t.Date.slice(0,10).replace(/-/g,'-')} )) 返回( 你过去的参赛作品: {items} ) } renderFollowActivities=()=>{ const items=this.state.follows.map((t,idx)=>( 报价编号:{t.Quote\U Nr} 来源:{t.Source_id} 状态:{t.Status\u id} 成本:${t.Cost} 返利:${t.retrieve} 日期:{t.Date.slice(0,10).replace(/-/g,'-')} )) 返回( {items} ) } getleads=()=>{ const id=“铅”; const dd=this.state.utc.slice(0,10).replace(/-/g,'-'); const count=this.state.therapists.filter((t)=>t.status\u id==id&&t.date.slice(0,10)。replace(/-/g,“-”)==dd.le