У меня проблема со связью между компонентами братьев и сестер - PullRequest
0 голосов
/ 22 марта 2019

Проблема в том, что у меня такая структура:

structure

Где компонент «FormNotas» - это форма, которую я отправляю информацию в API в бэкэнде, а компонент «TabelaNotas» отображает то, что приходит из базы данных. Проблема в том, что я не могу обновить компонент «TabelaNotas» при вводе записи через компонент «FormNotas».

Следуйте кодам ниже:

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 голосов
/ 23 марта 2019

Переместите коллекцию notas и функцию для отправки данных в API в общий родительский компонент и передайте их в качестве реквизитов каждому (функция в FormNotas, а коллекция в TableNotas). Это включает и FormNotas, и TableNotas в компоненты представления, которые делегируют свою логику компоненту контейнера, который может управлять обоими.

Для получения дополнительной информации о контейнерах и презентационных компонентах прочтите это .

...