我在兄弟姐妹组件之间的通信时遇到问题

时间:2019-03-22 18:18:32

标签: reactjs react-redux react-hooks

问题是以下我有这个结构:

structure

其中组件'FormNotas'是一种表单,我将信息发送到后端的API,而'TabelaNotas'组件则显示来自数据库的信息。这里的问题是,当我通过“ FormNotas”组件输入记录时,我无法更新“ TabelaNotas”组件。

遵循以下代码:

Notas.js

import React, {useState} from 'react'
import TabelaNotas from './TabelaNotas'
import {Button, Card, Icon} from 'antd'
import FormNotas from './FormNotas'

export default () => {

    const [exibirForm , setExibirForm] = useState({ exibirForm : false});

    function showForm(){
        setExibirForm({exibirForm : true})
    }

    function closeForm(){
        setExibirForm({exibirForm : false})
    }

    return (
        <>
             <div style={Styled.alinhamentoButton}>
                <Button type="primary" icon="plus" onClick={()=> showForm()}>Lançar Nota</Button>
            </div>
            {exibirForm.exibirForm === true ? 
            (
                <Card style={Styled.card}> 
                     <h4 style={Styled.h4}><Icon type="deployment-unit" /> Lançamento de nota</h4>
                    <Button type="dashed" style={Styled.buttonClose} onClick={()=> closeForm()}><Icon type="close" /></Button>
                    <FormNotas />
                </Card>
            ) : (<></>)}
            <TabelaNotas />
        </>
    )
}

const Styled = {
    buttonClose : {
        float: 'right',
        position: 'absolute',
        right: 0,
        top: 0,
        transform: 'translateX(-50%) translateY(50%)'
    },
    alinhamentoButton : {
        display: 'flex', 
        justifyContent: 'flex-end',
        marginBottom: '10px',
    },
    card : {
        marginBottom: 25,
        display: 'flex', 
        justifyContent: 'center',
        transition: 'all 1s ease-in-out 0s'
    },
    h4 : { 
        letterSpacing: '-0.5px',
        wordSpacing:'-4.5px',
    },
}
        

TabelaNotas.js

import React, {useState, useEffect, useReducer} from 'react'
import {API} from '../../Services/API/API'
import {Headers} from '../../Services/API/Headers'
import axios from 'axios'
import { Table, Card, Button } from 'antd'
import columns from './columnsTableNotas'


export default () => {
    const [ notas , setNotas] = useState({ data: [] , loading: true}, [])
    useEffect(() => {
        axios.post(API.urlBase , { query: ` {getNotaByUser(id: 1){ id Nota Referencia Tipo_nota Data_criacao materia_id{ Nome_Materia Professor Ano_letivo Data_criacao }}}` }, Headers)
        .then( resp => {
            setNotas({ data : resp.data.data.getNotaByUser, loading: false})
        })
    } , []);
    
    return (
        <Card>
            <Table dataSource={notas.data} columns={columns} loading={notas.loading} rowKey={record => record.id} />
        </Card>
    )
}

FormNotas.js

import React, {useEffect , useState } from 'react'
import {Form, Select, Input, Button, message} from 'antd'
import {API} from '../../Services/API/API'
import {Headers} from '../../Services/API/Headers'
import axios from 'axios'

export default () => {

    const [dados, setDados] = useState({ materias : [] , loading: true , cbxMateria : '', txtNota: null, cbxReferencia: '1' , cbxTipo: 'Prova'}) 

    useEffect(() => {
        axios.post(API.urlBase, { query: `{getMateriaByUser(id : ${API.userBase}){id Nome_Materia Professor Ano_letivo Data_criacao  user_id{ id }}}` }, Headers)
        .then( resp => {
            setDados({ ...dados, materias: resp.data.data.getMateriaByUser, loading: false})
        })
    }, []);

    function salvarFormulario(e){
        e.preventDefault();
        axios.post(API.urlBase, { query: `mutation { newNota(input: {Nota: ${dados.txtNota}, Referencia: "${dados.cbxReferencia}", Tipo_nota: "${dados.cbxTipo}", materia_id : ${dados.cbxMateria}, user_id: ${API.userBase}}) {id Nota Referencia Tipo_nota Data_criacao}}`}, Headers)
        .then( resp => {
            message.success('Materia inserida com sucesso!')
            setDados({...dados, cbxMateria : '', txtNota: null, cbxReferencia: '1' , cbxTipo: 'Prova'})
        })
    }

    function AtualizarInput(e){
        setDados({...dados, [e.target.name] : e.target.value})
    }

    function AtualizarSelect(nome , e){
       setDados({...dados, [nome] : e})
    }

    return (
            
            <Form layout="inline" method="post" onSubmit={ e => salvarFormulario(e)}>
                <Form.Item>
                    <Select name="cbxMateria" onSelect={(e) => AtualizarSelect("cbxMateria" , e)} placeholder="Disciplina" style={styled.select} loading={dados.loading} defaultActiveFirstOption={true}>
                        {dados.materias.map( (res , i ) => {
                            return (
                                <Select.Option key={i} value={res.id}>{res.Nome_Materia}</Select.Option>
                            )
                        })}
                    </Select>
                </Form.Item>
                <Form.Item>
                    <Input type="text" name="txtNota" placeholder="Nota" required  style={styled.input} value={dados.txtNota} onChange={AtualizarInput}/>
                </Form.Item>
                <Form.Item>
                    <Select defaultValue='1' name="cbxReferencia" style={styled.select} value={dados.cbxReferencia} onSelect={(e) => AtualizarSelect("cbxReferencia" , e)}>
                            <Select.Option value="1">1º Referência</Select.Option>
                            <Select.Option value="2">2º Referência</Select.Option>
                            <Select.Option value="3">3º Referência</Select.Option>
                            <Select.Option value="4">4º Referência</Select.Option>
                    </Select>
                </Form.Item>
                <Form.Item>
                    <Select defaultValue='Prova' name="cbxTipo" style={styled.select} value={dados.cbxTipo} onSelect={(e) => AtualizarSelect("cbxTipo" , e)}>
                            <Select.Option value="Prova">Prova</Select.Option>
                            <Select.Option value="Trabalho">Trabalho</Select.Option>
                            <Select.Option value="Nota Extra">Nota Extra</Select.Option>
                    </Select>
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" htmlType="submit" name="Send" icon="plus">Salvar registro</Button>
                    </Form.Item>
            </Form>
    )
}

const styled = {
    input:{ 
        width: 150
    },
    select : {
        width: 150
    }
}

1 个答案:

答案 0 :(得分:0)

将notas集合和用于将数据发送到API的函数移动到一个公共父组件,并将它们作为道具传递给每个父组件(该函数传递给FormNotas,该集合传递给TableNotas)。这会将FormNotas和TableNotas都覆盖到表示性组件中,这些组件将其逻辑委托给可以控制两者的容器组件。

有关容器和外观组件的更多信息,read this