簡體   English   中英

子組件向數據庫添加元素時如何重新渲染父組件?

[英]How to re-render the parent component when the child component adds an element to the database?

我有兩個組件“父”和“子”。 在“父”組件中,我使用“axios”獲得了一個元素數組。 “子”組件是一個“模態”,它有一個輸入和一個向數組添加元素的發送按鈕。

獲取項目並將它們添加到數據庫中工作正常。 我使用的數據庫是MongoDB,后端有node和express。

當我使用“子”組件添加新元素時,如何讓“父”組件呈現? 目前,當使用“子”組件添加新元素時,數據庫會更新,但“父”組件不會。 當我刷新頁面時,父組件會更新,然后它會從數據庫中呈現更新的表。

Component Parent (main fragment):

class ShoppingList extends Component {
constructor(props){
    super(props)
    this.state = {
        items: []
    }
}

componentDidMount(){
    this.getPosts();
}

getPosts(){
    axios.get('/api/items')
        .then(res=>{const arrayItems = res.data;this.setState({items: arrayItems})})
        .catch(err=>console.log(err))
}

會這樣做:在數據更新時通知父級,並在收到此通知時強制父級重新渲染:

父.js

class ShoppingList extends Component {
constructor(props){
    super(props)
    this.state = {
        items: []
    }
}

componentDidMount(){
    this.getPosts();
}

getPosts(){
    axios.get('/api/items')
        .then(res=>{const arrayItems = res.data;this.setState({items: arrayItems})})
        .catch(err=>console.log(err))
}

return (
        <Child notifyParent={() => this.forceUpdate()} />
);
}

Child.js

class Child extends Component {
    updatePost() {
        axios.post('...', something)
        .then(resp => {
            //...
            this.props.notifyParent();
        });
    }
}

如您所知,預渲染會導致 state 更改或道具。

在“父”組件中,我向 state 添加了“update: false”。 我創建了“myForceUpdate”function,其中我更改了“update: true”state 將“myFirceUpdate”function 傳遞給“child”組件。 在“child”組件中,我將“props”放入“then”。

向數組添加元素時,“父”組件中的“myForceUpdate”function 啟動並更改“父”組件的 state,但不會重新渲染。

我究竟做錯了什么?

Parent:                                                                           
class ShoppingList extends Component {
 constructor(props){
    super(props)
    this.state = {
        items: [],
        update: false
    }
}

componentDidMount(){
    this.getPosts();
    this.setState({
        update: true
    })
    console.log('CDM')
}

getPosts(){
    axios.get('/api/items')
        .then(res=>{const arrayItems = res.data;this.setState({items: arrayItems})})
        .catch(err=>console.log(err))
}

onDeleteClick = (id) => {
    axios.delete(`/api/items/${id}`)
        .then(()=>{this.setState({items: this.state.items.filter(item=>item._id!==id)})})
        .catch(err=>console.log(err)) 
}

myForceUpdate = () => {
    console.log('myForceUpdate')
    this.setState({
        update: true
    })
    console.log(this.state.update)
}

render(){
    return(
        <Container>
            <ItemModal addPost={this.myForceUpdate}/>

Child:
axios.post('/api/items',newItem)
       .then(res=>console.log(res.data))
       .then(()=>this.props.addPost())
       .catch(err=>console.log(err))

通過使用componentDidMount和componentDidUpdate得到了上述問題的解決方案。

Parent:
...
constructor(props){
        super(props)
        this.state = {
            items: [],
            update: false
        }
    }

    componentDidMount(){
        this.getPosts();
    }

    componentDidUpdate(){
       if(this.state.update === true){
            this.getPosts();
            this.setState({
                update: false
            })
        }
    }
...
myForceUpdate = () => {
        this.setState({
            update: true
        })
    }

    render(){
        return(
            <Container>
                <ItemModal addPost={this.myForceUpdate}/>
...

Child:
...
axios.post('/api/items',newItem)
       .then(()=>this.props.addPost())
       .catch(err=>console.log(err))                                                
...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM