【问题标题】:Call a function of class component for setting state , but values not updating调用类组件的函数来设置状态,但值不更新
【发布时间】:2022-07-07 19:35:28
【问题描述】:

api-service.js 代码

import CustomToaster from "../toaster/toaster";

export async function saveData(){
    return new Promise(async(resolve)=>{
        try {
            let res=await fetch('http://localhost:5000/test',{
                //mode: 'no-cors'
                headers:{ "authorization":"my-auth-token" }
            })
    
            const data = await res.json();
    
           return resolve(data)
        } catch (error) {
            console.log(error)
            showAlert(error)
        }

    })
}
export async function showAlert(err){
    let d = new CustomToaster()
    await d.componentDidMount()
    d.setToaster('hello','my world',12)
    
}

toaster.js 代码

import { Component } from "react";
import { Toast } from "react-bootstrap";

class CustomToaster extends Component {
    
    

    constructor(props) {
        super(props)    
        this.state={
            title:'no title',
            time:'2 min',
            description:'no desription',
            show:false
        }
    }
    componentDidMount(title, description='',time='',delay=5000){
        return new Promise((resolve)=>{
            resolve(true)
        })
    }
    setToaster = (title, description='',time='',delay=5000)=>{
        if(title){
            this.setState(() => ({
                title:title
            }))
        }
        if(time){
            this.setState({
                time:time
            })
        }
        if(description){
            this.setState({
                description:description
            })
        }
        this.setState({
            show:true
        })

    }
    render() {
        return (
            <Toast show={this.state.show} delay='2000' autohide>
                <Toast.Header>
                    <img src="holder.js/20x20?text=%20" className="rounded me-2" alt="" />
                    <strong className="me-auto">{this.state.title}</strong>
                    <small>{this.state.time}</small>
                </Toast.Header>
                <Toast.Body>{this.state.description}</Toast.Body>
            </Toast>
        )
    }
}

export default CustomToaster;

setToaster 函数无法设置状态我也收到警告 无法在尚未安装的组件上调用 setState。这是一个无操作,但它可能表明您的应用程序中存在错误。而是直接分配给 this.state 或在 CustomToaster 组件中定义具有所需状态的 state = {}; 类属性。

【问题讨论】:

标签: javascript reactjs mern


【解决方案1】:

这不是您创建或安装组件的方式:

// Not how you do this
let d = new CustomToaster()

相反,您通过ReactDOM.renderrender on a rootin a portal 在另一个组件的render 函数中渲染该组件。

您从 setState 收到该错误,因为这不是您创建或安装组件的方式。

如果您需要对组件实例的引用以便对其调用方法,则需要在其上使用 ref 并在引用的 current 属性上调用该方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-18
    • 1970-01-01
    • 2019-02-18
    • 2021-08-24
    • 1970-01-01
    • 2019-10-31
    • 2022-01-23
    • 2021-05-26
    相关资源
    最近更新 更多