[英]SetState from props dict in react js?
我是Reactjs的新手,我坚持解决问题,从props字典设置状态。 我的代码如下所示:
this.state = {
test: []
}
render() {
this.props.data.map(function(item, key){
this.setState({ test: data.name})
})
}
没有用,有人对如何做有任何想法。 谢谢,我一直在做一些更改:
componentDidMount() {
this.state.userData.then(data => this.props.getData(data.user["data"]). then(test => this.setState(test.test.map(item => item.name))))}
state.test仍然为空。
您无法在render
函数中设置状态,这将导致无限循环。
正确的方法
constructor(props){
super(props)
this.state = {
test: props.data.map(item => item.name)
}
}
render(){
return (
{this.state.test.map(item => {
return (
<p>{item}</p>
)
})}
)
}
尝试遵循此模式将有助于您编写简洁的代码。
还可以看出,我已经将道具直接放在构造函数中,因为在某些情况下道具可以直接用于组件。
如果您想发出请求,然后在注入道具后,您可以在componentWillReciveProps或某些Hooks方法(如果您使用react钩子)中进行处理
import React ,{Component,Fragment} from "react";
import ReactDOM from "react-dom";
import "./styles.css";
class App extends Component {
constructor(props){
super(props)
this.state ={
//This can be done if the prop is props are available before component renders
test: this.props.data||[1,2,3,4]
}
}
render(){
let {test} = this.state
return(
<Fragment>
{test.map((it,i) => <div key={i} >{it}</div>)}
</Fragment>
)
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.