![](/img/trans.png)
[英]Using this.setState with update from immutability-helper is not re-rendering React Component
[英]updating react component state using this.setState isn't re-rendering the component
我正在使用react.setState()方法更新react組件的狀態,該狀態中的值正在更新,但是組件不會使用更新后的值重新呈現。
class Mission extends React.Component { constructor() { super(); this.state = { missonContents: [this.missonContent[0]] }; } missonContent = [{ id: "approach", data: "Visit Farmers to review their self-sustenance ideas, provide counselling and suggest suitable options. Rather than one time donation, we support the farmers until they become self-sustain." }, { id: "plan", data: " Fund 90% for each Farmer's self sustenance Idea and request the Farmer to contribute 10% to create responsibility." }, { id: "goal", data: "Develop a working model to make Poor Farmers self-sustain. Involve in Policy advocation at District or State level that supports small farmers." } ]; /** This method gets called in the componentDidMount() */ animateMission() { /** some code here */ // updating the state not rerendering the component this.setState({ "missonContents": [this.missonContent[0], this.missonContent[1]] }); } render() { //console.log(this.state["missonContents"]); const missionCarousel = this.state["missonContents"].map((missionContent) => { // console.log(missionContent); return <b > < p id = { missionContent.id } className = "fontsize20" > { missionContent.data } < /p></b > }); return ( < div className = "col l12 m12 s12 margintop50 card" > { missionCarousel } < /div> ); } }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.0/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.0/umd/react-dom.production.min.js"></script>
我認為函數animateMission()不在與類的綁定中,如果是這樣,我該怎么辦?
您的代碼中存在一些問題。 1)首先,在構造函數中綁定animateMission
方法this.animateMission = this.animateMission.bind(this);
或使用箭頭功能。
2)您有一些拼寫錯誤。 this.setState({missonContents : [this.missonContent[0],this.missonContents[1]]}); // updating the state not rerendering the component
這里this.missonContents[1]
和this.missonContent[0]
具有不同的拼寫。
在您的animstemission()
嘗試一下,設置狀態后,調用componentdidmount()
我希望它能工作
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.