我的目标是仅使用初始 Json 中的一部分数据来更新父组件的状态
所以基本上,如果例如 text
被触发:
1-我返回所需的文本
并将其呈现在我的组件中(我成功地做到了这一点)
2-我还想获取此特定数据并将其存储在父状态中
3-我稍后将使用此数据创建表单
我尝试了很多方法,最终成功通过将函数传递给无状态函数MyFunction
来更新父级的状态,但我不断收到>警告,因为setState
正在父组件
的render
方法内调用
警告:无法在现有状态转换期间进行更新(例如在
render 或其他组件的构造函数内)。
const MyFunction = props => {
switch (props.type) {
case 'image':
return props.json.data[props.key]
break
case 'text':
props.changeParent(props.json.data[props.key])
return props.json.data[props.key]
break
default:
return "Empty text"
break
}
}
class UserComponent extends Component {
constructor(props){
super(props)
this.state = {
active: false
}
}
render(){
return(
<div>
{ MyFunction({ type: 'text', key: 'first_name', ...this.props }) }
<img src={ MyFunction({ type: 'image', key: 'avatar', ...this.props }) } />
</div>
)
}
}
// Parent Component
class App extends Component {
constructor(props){
super(props)
this.state = {
json:[],
newJson: []
}
}
// Fetching data from an api
componentDidMount(){
fetch("https://reqres.in/api/users/2")
.then(response => response.json())
.then(json => {
this.setState({json: json })
})
}
// Update the parent Json using the data sent from the 2nd child
changeParent(jsonToUpdate){
this.setState({
newJson :
jsonToUpdate
})
}
render() {
return (
<div>
<UserComponent {...this.state} changeParent={(jsonToUpdate) => this.changeParent(jsonToUpdate)}/>
</div>
);
}
}
export default App;
最佳答案
只需使用 componentDidMount
生命周期方法并维护 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>
)
}
}
更新::
如果您多次调用 MyFunction
,则应避免在 MyFunction
内调用 changeParent
,因为您正在调用 MyFunction
> 在渲染内并在渲染内调用 changeParent
会将其放入循环中,因为您正在 changeParent
函数中更新父状态。根据给定的代码我能想到的更好的解决方案是这样的
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 中使用 MyFunction
调用 changeParent
就像
componentDidMount(){
let myFunctionReturnData = MyFunction({ type: 'text', key: 'first_name', ...this.props });
// Call the parent function
this.props.changeParent(myFunctionReturnData)
}
您现在不需要维护任何状态。
关于javascript - 如何通过调用无状态组件中开关内的函数来更新父状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46476830/