简体   繁体   English

来自React JS中的props dict的SetState?

[英]SetState from props dict in react js?

I am new to reactjs and I am stuck on solving a problem, set a state from props dictionary. 我是Reactjs的新手,我坚持解决问题,从props字典设置状态。 My code looks like this: 我的代码如下所示:

this.state = {
    test: []
}
render() {
  this.props.data.map(function(item, key){
  this.setState({ test: data.name})
})
}

Is not working, does anyone have any ideas of how to do it. 没有用,有人对如何做有任何想法。 Thanks I've been doing some changes: 谢谢,我一直在做一些更改:

componentDidMount() {
     this.state.userData.then(data => this.props.getData(data.user["data"]). then(test => this.setState(test.test.map(item => item.name))))}

Still the state.test is empty. state.test仍然为空。

You can't set a state in the render function, this will cause an infinite loop. 您无法在render函数中设置状态,这将导致无限循环。

The correct way 正确的方法

constructor(props){
  super(props)

  this.state = {
    test: props.data.map(item => item.name)
  }
}

render(){
  return (
    {this.state.test.map(item => {
      return (
        <p>{item}</p>
      )
    })}
  )
}

Try following this pattern will help you write clean code. 尝试遵循此模式将有助于您编写简洁的代码。

Also as can be seen that i have put the props directly within the constructor because it may be the case where the props are directly available to the component. 还可以看出,我已经将道具直接放在构造函数中,因为在某些情况下道具可以直接用于组件。

in case you want to make request and then after inject the props u can handle the same in the componentWillReciveProps or some Hooks method if your using react hooks 如果您想发出请求,然后在注入道具后,您可以在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM