Javascript 如何通过调用无状态组件中开关内的函数来更新父状态?
我的目标是只使用来自初始Json的一部分数据更新父组件的状态 因此,基本上如果案例Javascript 如何通过调用无状态组件中开关内的函数来更新父状态?,javascript,reactjs,Javascript,Reactjs,我的目标是只使用来自初始Json的一部分数据更新父组件的状态 因此,基本上如果案例text被触发: 1-我返回所需的文本并在我的组件中呈现它(我成功地做到了) 2-我还想获取此特定数据并将其存储在父状态中 3-稍后我将使用此数据创建表单 我尝试了很多方法,最终通过将函数传递给无状态函数MyFunction,来更新父级的状态,但我一直收到警告,因为在父级组件的render方法中调用了setState 警告:在现有状态转换期间(例如在render或其他组件的构造函数中)无法更新。 constmyfu
text
被触发:
1-我返回所需的文本
并在我的组件中呈现它(我成功地做到了)
2-我还想获取此特定数据并将其存储在父状态中
3-稍后我将使用此数据创建表单
我尝试了很多方法,最终通过将函数传递给无状态函数MyFunction
,来更新父级的状态,但我一直收到警告,因为在父级组件的render
方法中调用了setState
警告:在现有状态转换期间(例如在
render或其他组件的构造函数中)无法更新。
constmyfunction=props=>{
开关(道具类型){
案例“图像”:
返回props.json.data[props.key]
打破
案例“文本”:
changeParent(props.json.data[props.key])
返回props.json.data[props.key]
打破
违约:
返回“空文本”
打破
}
}
类UserComponent扩展组件{
建造师(道具){
超级(道具)
此.state={
活动:错误
}
}
render(){
返回(
{MyFunction({type:'text',key:'first_name',…this.props})}
)
}
}
//父组件
类应用程序扩展组件{
建造师(道具){
超级(道具)
此.state={
json:[],
newJson:[]
}
}
//从api获取数据
componentDidMount(){
取回(“https://reqres.in/api/users/2")
.then(response=>response.json())
。然后(json=>{
this.setState({json:json})
})
}
//使用从第二个子系统发送的数据更新父Json
changeParent(jsonToUpdate){
这是我的国家({
newJson:
jsonToUpdate
})
}
render(){
返回(
this.changeParent(jsonToUpdate)}/>
);
}
}
导出默认应用程序;
只需使用componentDidMount
lifecycle方法,并为myFunction
返回的数据维护一个状态,即可避免类似这样的警告
class UserComponent extends Component {
constructor(props){
super(props)
this.state = {
active: false,
// this state stores the data returned by function
myFunctionReturnData: ""
}
}
componentDidMount(){
let myFunctionReturnData = MyFunction({ type: 'text', key: 'first_name', ...this.props });
// Call the function and set the state by returned value
this.setState({ myFunctionReturnData })
}
render(){
return(
<div>
// Will render returned value when state will be set
{ this.state.myFunctionReturnData }
<img src={ MyFunction({ type: 'image', key: 'avatar', ...this.props }) } />
</div>
)
}
}
在componentDidMount中,使用MyFunction
调用changeParent
类似
componentDidMount(){
let myFunctionReturnData = MyFunction({ type: 'text', key: 'first_name', ...this.props });
// Call the parent function
this.props.changeParent(myFunctionReturnData)
}
您现在不需要维护任何状态。您的解决方案给出了相同的警告,实际上MyFunction({type:'text',key:'first_name',…this.props})
必须被调用UserComponent
的返回语句,因为我在那里使用返回值,我会用不同的参数多次调用它。这不是我的目标,想象一下,我用不同的参数在“myParent”的render方法中调用MyFunction 6次。因此,基本上,对于每个函数调用,我都希望在状态中存储这些单独的值。因此,对于每次调用,我将存储'type:'xxx',key:'xxx',以便稍后我可以使用此数据创建一个表单,例如
const MyFunction = props => {
switch (props.type) {
case 'image':
return props.json.data[props.key]
break
case 'text':
// Remove changeParent from here
return props.json.data[props.key]
break
default:
return "Empty text"
break
}
}
componentDidMount(){
let myFunctionReturnData = MyFunction({ type: 'text', key: 'first_name', ...this.props });
// Call the parent function
this.props.changeParent(myFunctionReturnData)
}