我正在使用Reactjs处理表单,该表单从父组件获取一些defaultValues。
问题是,父组件使用axios帖子设置值的状态,并将这些值作为道具传递给子级。我可以使用console.log在子组件上打印这些值,但是如果尝试将这些值放在TextField的defaultValues上,则会得到一个空窗体,该窗体上不会呈现任何值。
父组件:
export default class Parent extends Component {
constructor(props){
super(props);
this.state={
somevalue: '',
}
}
componentDidMount(){
this.getData();
}
getData = async () => {
await api.post('/getValue')
.then((res) => {
this.setState({
someValue: res.data;
})
}).catch((err) => {
console.log("Error: ", err);
})
}
render(){
return(
<Child value={this.state.someValue}/>
)}
}
子组件
export default function Child(props) {
console.log(props.value); // THIS LOG PRINT THE VALUE PROPERLY
return(
<TextField defaultValue={props.value}/>
)
}
这基本上是我的代码结构,但是不起作用。此后TextField仍然为空。
答案 0 :(得分:2)
属性defaultValue
仅用于初始渲染。如果您检查代码,则会在console.log输出值之前看到,它将首先输出undefined
。您可以通过将defaultValue
更改为value
来将其更改为受控组件。这样就可以显示值,但是您需要为该值的更改添加一个onChange处理程序。
function Child(props) {
// Using the value prop your value will display, but you will also have to pass an onChange handler to update the state in the parent
return <TextField value={props.value} />;
}
或者您可以等到该值可用后再渲染组件
const { someValue } = this.state;
if (!someValue) {
return "loading the data";
}
return <Child value={someValue} />;
取决于具体情况,哪种解决方案会更好。但是我认为您可能想要更新输入中的值并对其进行处理,所以我会考虑第一种情况。