我正在使用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()函数与该类没有绑定,如果可以,该怎么办?
答案 0 :(得分:2)
您的代码中存在一些问题。
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]
具有不同的拼写。
答案 1 :(得分:0)
在您的animstemission()
中尝试一下
设置状态后componentdidmount()
我希望它能起作用