簡體   English   中英

來自React JS中的props dict的SetState?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM