1: componentDidMoun(){}里不能直接更新stete,不能setState({}); 解决方法,在setTimeOut({})里设置setState
例:componentDidMount() {
setTimeout( _ => {
this.setState({ val: this.state.val + 1 })
console.log(this.state.val) // 输出更新后的值 --> 1
}, 0)
2:关于react的this.setState异步问题,setState数据不更;
通过setState的回调函数解决,
setState({
name:‘Tom’,
},()=>{
console.log()
}
)
参考文档 :https://blog.csdn.net/Chris__wang/article/details/82625933
3.react关于父子之间的传值问题
React父组件与子组件之间的值传递
一、父组件向子组件传递信息
将父组件的state通过props传入子组件
父组件代码片段
constructor(props){
super(props)
this.state={
message:“父组件的值,子可以直接使用”
}
}
render(){
return(
<div style={{background:“red”,padding:“30px”}}>
/将要传给子组间的值
)
}
}
子组件代码片段
class Son extends React.Component{
render(){
console.log(this.props.msg)
return(
<button style={{width:“100px”,height:“50px”}} onClick={()=>{this.props.cancel(需要传出的值)}}>返回
父组件传到子组件的信息:<span style={{background:“white”}}>{this.props.msg}
)
}
}
总结:父传子直接用props传就行,子传给父:需要在子组件中自定义一个this.props中需要传出的值,在父组件中拿到这个值得方法。详见例子。
原文:https://blog.csdn.net/margin_0px/article/details/81359189
react项目搭建:参考:https://www.jb51.net/article/140145.htm