简体   繁体   English

如何将数据传递给我的子组件?

[英]How can I pass data to my child component?

I try to pass data (like an object) from one component to another but I always get an empty object.我尝试将数据(如对象)从一个组件传递到另一个组件,但我总是得到一个空的 object。

  1. I call an async function to get data.我调用异步 function 来获取数据。
  2. I use the setTeamAData / setTeamBData to populate the object我使用 setTeamAData / setTeamBData 来填充 object
  3. I pass to my child component TeamA / Team B as "data"我作为“数据”传递给我的子组件 TeamA / Team B
  4. when I print props.data I always get {}当我打印 props.data 时,我总是得到 {}
import React, { useEffect, useState } from 'react';
import Team from './Team';
import PlayerSelect from './PlayerSelect';
import axios from 'axios';
import moment from 'moment';

function Match(props) {
    const [id, setId] = props.match.params.id;
    const [teamAData, setTeamAData] = useState({});
    const [teamBData, setTeamBData] = useState({});
    const [location, setLocation] = useState(0);
    const [datetime, setDatetime] = useState(moment(Date.now()).format("YYYY-MM-DDTkk:mm"));
    const [locations, setLocations] = useState([]);
    const [teamA, setTeamA] = useState([0,0,0,0,0]);
    const [teamB, setTeamB] = useState([0,0,0,0,0]);
    const [teamAName, setTeamAName] = useState('');
    const [teamBName, setTeamBName] = useState('');
    const [teamAScore, setTeamAScore] = useState(0);
    const [teamBScore, setTeamBScore] = useState(0);
    const [pichichi, setPichichi] = useState(['']);
    const [mvp, setMVP] = useState([]);

    useEffect(() => {
        console.log('USE EFFECT!')
        async function fetchLocations() {
            const response = await axios.get('locations');
            setLocations(response.data);
        }
        fetchLocations();

        async function fetchMatch(id) {
            const response = await axios.get(`matches/${id}`);
            const match = response.data;
            setLocation(match.location);
            setTeamAData({name: response.data.teamAName});
            setTeamBData({name: response.data.teamBName});
            setTeamAScore(match.teamAScore);
            setTeamBScore(match.teamBScore);
            setPichichi(match.pichichi);
        }
        if (props.match.params.id)
            fetchMatch(props.match.params.id);
    }, []);

    async function handleSubmit(event) {
        event.preventDefault();
        const response = await axios.post('matches', {
            location: location,
            datetime: datetime,
            teamAName: teamAName,
            teamA: teamA,
            teamAScore: teamAScore,
            teamB: teamB,
            teamBName: teamBName,
            teamBScore: teamBScore,
            pichichi: pichichi,
            mvp: mvp
        });
    }

    function handlePlayerChange(teamId, ddId, value) {
        let team = teamA; 
        if (teamId == 'B')
            team = teamB;
        team[ddId[1]] = value;
        if (teamId == 'A')
            setTeamA(team);
        else
            setTeamB(team);
    }

    function handleNameChange(teamId, name) {
        if (teamId == 'A')
            setTeamAName(name);
        else
            setTeamBName(name);
    }
    return (
        <div>
        <form onSubmit={handleSubmit}>
            <div className="field">
                <div className="label">Location:</div>
                <div className="control">
                <div className="select">
                    <select onChange={e=> setLocation(e.target.value)} value={location}>
                    <option value="0">---</option>
                    {
                        locations.map(location => 
                            <option value={location._id} key={location._id}>{location.name}</option>
                        )
                    }
                    </select>
                </div>
                </div>
            </div>
            <div className="field">
                <div className="label">Date / time :</div>
                <div className="control">
                    <input type="datetime-local" className="input" value={datetime} onChange={(e) => setDatetime(e.target.value)}/> 
                </div>
            </div>
            <div className="columns">
                <div className="column">
                    <Team id="A" 
                        data={teamAData}
                        onNameChange={handleNameChange}
                        onPlayerChange={handlePlayerChange}/>
                </div>
                <div className="column">
                    <Team id="B" 
                        data={teamBData}
                        onNameChange={handleNameChange}
                        onPlayerChange={handlePlayerChange}/>
                </div>
            </div>
            <div className="field">
                <div className="label">Score A</div>
                <div className="control">
                    <input type="text" value={teamAScore} onChange={e=> setTeamAScore(e.target.value)}/>    
                </div>
            </div>
            <div className="field">
                <div className="label">Score B</div>
                <div className="control">
                    <input type="text" value={teamBScore} onChange={e=> setTeamBScore(e.target.value)}/>    
                </div>
            </div>
            <div className="field">
                <div className="label">Pichichi</div>
                <div className="control">
                    <PlayerSelect multiple value={pichichi}/>   
                </div>
            </div>
            <div className="field">
                <div className="label">MVP</div>
                <div className="control">
                    <PlayerSelect value={mvp}/> 
                </div>
            </div>
            
            <button className="button is-primary" type="submit">Create</button>
        </form>

        
        </div>
    )
}

export default Match;

This is the child component:这是子组件:

import React, { Fragment, useEffect, useState } from 'react';
import PlayerSelect from './PlayerSelect';

function Team(props) {
    console.log(props)
    const [numberOfPlayers, setNumberOfPlayers] = useState(6);
    const [players, setPlayers] = useState([]);
    const [name, setName] = useState(props.data.name);

    useEffect(() => {
    }, []);

    function handlePlayerChange(id, value) {
        let p = players;
        p.push(value)
        setPlayers(p);
        props.onPlayerChange(props.id, id, value);
    }

    function addPlayer(event) {
        setNumberOfPlayers(numberOfPlayers+1);
    }

    function removePlayer(event) {
        setNumberOfPlayers(numberOfPlayers-1);
    }

    function handleNameChange(event) {
        event.preventDefault();
        setName(event.target.value);
        props.onNameChange(props.id, event.target.value);
    }

    let dds = []
    for (let i = 0; i < numberOfPlayers; ++i) {
        const id = `${props.id}${i}`;
        dds.push(
            <PlayerSelect key={id} id={id} onChange={handlePlayerChange}/>
        )
    }
    const placeholderName = `Team ${props.id}`;
    return (
        <>
            <div className="control">
                <input type="text" value={name} onChange={handleNameChange} className="input" placeholder={placeholderName}/>
            </div>
            {/*<button className="button" onClick={addPlayer}>+</button><br/>*/}
            {dds}
        </>
    )
}

export default Team;

data is only ever {} when the children components mount and name state is initialized.只有当子组件挂载并且name state 被初始化时, data才永远是{}

const [name, setName] = useState(props.data.name);

If the data prop is asynchronously updated then the children components need to also handle the data prop updating later.如果data prop 是异步更新的,那么子组件也需要稍后处理data prop 更新。 Use an useEffect hook with a dependency on the data prop` to update the local state when it updates from the parent component.当本地 state 从父组件更新时,使用依赖于data prop` 的useEffect挂钩。

useEffect(() => {
  setName(props.data.name);
}, [props.data.name]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将数据传递给子组件? - How do I pass the data to the child component? 就我而言,如何将数据从子组件传递到父组件? - In my case, how to pass data from child component to parent component? 如何将我的数据传递到 ReactBnbGallery 组件? - How can I pass my data into ReactBnbGallery component? 如何使用 React 钩子将我的 Todo 组件数据传递到我的 Todolist 组件中? - How can I pass my Todo component Data into my Todolist component using React hooks? 如何将子组件中的表单数据传递给父组件(也包含表单)并在提交日志时提交所有数据? - How do I pass my Form Data which is in the child component to the parent component(which also contains a form) and on submit log all the data? 如何将状态从这个子组件传递给父组件? - How can I pass the state from this child to parent component? 如何将子组件的 state 传递给父组件? - How can I pass a child component's state up to the parent? 如何将 id 从子组件传递到父组件? - How can I pass the id from child to parent component? 如何将使用 TypeScript 的 useState 道具传递给子组件 - how can I pass a useState props using TypeScript to a child component 如何将接口传递给 Typescript React 应用程序中的子组件 - How can I pass Interface to the child component in Typescript React application
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM