[英]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。
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.