我有2个组成部分。 UpdateAudio(父组件)和AudioForm(子组件)。
我从componentDidMount方法中的API获取数据,并在UpdateAudio组件中更新音频状态,并将此音频作为音频形式传递给AudioForm。
现在,当我在AudioForm中的渲染器中看到console.log(this.props.audio)时,我可以看到新的音频值即将到来,但是表单不显示数据。是空白
UpdateAudio.js
import React, { Component, Fragment } from 'react';
import { withRouter } from 'react-router-dom';
import { Mutation, Query, graphql } from 'react-apollo';
import { UpdateAudioQuery, GetAudio } from '../query';
import { Button, Grid, LinearProgress } from '@material-ui/core';
import AudioForm from '../components/AudioForm';
import AudioSaveUpdateButton from '../components/AudioSaveUpdateButton';
import { withApollo } from 'react-apollo';
class UpdateAudio extends Component {
constructor(props) {
super(props);
this.site = "5d517862-0630-431c-94b1-bf34de6bfd8b"
this.state = {
audio: {
site: this.site,
title: '',
desc: '',
}
};
this.updateCache = this.updateCache.bind(this);
this.handleChange = this.handleChange.bind(this);
}
updateCache = (cache, { data }) => {
if (data.createAudio.audio.guid) {
console.log("redirecting...")
this.props.history.push('/audios')
}
}
handleChange = event => {
const { name, value } = event.target;
this.setState(prevState => ({
audio: {
...prevState['audio'],
[name]: value,
}
}));
};
componentDidMount = async () => {
let resp = await this.props.client.query({
query: GetAudio,
variables: {site: this.site, guid: this.props.match.params.guid}
})
let { data } = resp;
let audio = data.getAudio;
this.setState(prevState => ({
audio: {
...prevState['audio'],
...audio
}
}));
}
render() {
return (
<Fragment>
<AudioForm audio={this.state.audio} handleChange={this.handleChange} />
<AudioSaveUpdateButton create={false} audio={this.state.audio} updateCache={this.updateCache} />
</Fragment>
)
}
}
UpdateAudio = withRouter(UpdateAudio)
export default withApollo(UpdateAudio);
AudioForm.js
import React, {Fragment} from 'react';
import { TextField, Grid } from '@material-ui/core';
class AudioForm extends React.Component {
render() {
console.log(this.props.audio.title, this.props.audio.desc);
console.log(this.props.audio);
return (
<Fragment>
<form noValidate autoComplete="off">
<Grid container spacing={24} alignItems="center" justify="center">
<Grid item md={4} xs={12}>
<TextField
id="audio-title"
name="title"
label="Title"
margin="normal"
variant="outlined"
InputLabelProps={{ shrink: true }}
fullWidth
defaultValue={this.props.audio.title}
onChange={this.props.handleChange}
required
/>
</Grid>
<Grid item md={4} xs={12}>
<TextField
id="audio-desc"
name="desc"
label="Description"
margin="normal"
variant="outlined"
InputLabelProps={{ shrink: true }}
fullWidth
defaultValue={this.props.audio.desc}
onChange={this.props.handleChange}
required
/>
</Grid>
</Grid>
</form>
</Fragment>
);
}
}
export default AudioForm;
感谢您的帮助。