子组件:
class Children extends Component { constructor(props) { super(props); this.state = { a: this.props.a, b: this.props.b, treeData: ‘‘, targets: ‘‘, } } componentDidMount() { const { a, b } = this.state const data = {a,b} fetch(‘/Url‘, { data }).then(res => { if (res.code === 0) { this.setState({ treeData: res.a, targets: res.b, }) } else { message.error(res.errmsg) } }) } test(item1, item2) { const data = { item1, item2 } fetch(‘/Url‘, {data}).then(res => { if (res.code === 0) { this.setState({ treeData: res.a, targets: res.b, }) } else { message.error(res.errmsg) } }) }
} export default Children
方法一:巧用key
<Children key={this.state.key} a={this.state.a} b={this.state.b} /> //父组件调用子组件
这种方法是通过key变化对子组件不断实例化,react的key变化会销毁组件在重新实例化组件
方法二:利用ref父组件调用子组件函数(不符合react设计规范,但可以算一个逃生出口嘻嘻~)
class father extends Component { constructer(props) { super(props); this.state={
a: ‘1‘,
b: ‘2‘,
} this.myRef this.test = this.test.bind(this) } change() {
const { a,b } = this.state console.log(this.myRef.test(a,b)) // 直接调用实例化后的Children组件对象里函数 } render() { <Children wrappedComponentRef={(inst) => { this.myRef = inst } } ref={(inst) => { this.myRef = inst } } /> <button onClick={this.test}>点击</button> } }
注:wrappedComponentRef是react-router v4中用来解决高阶组件无法正确获取到ref
方法三:父级给子级传数据,子级只负责渲染(最符合react设计观念)推荐!!
父组件:
class father extends Component { constructer(props) { super(props); this.state={ a:‘1‘, b:‘2‘, data:‘‘, } } getcomposedata() { const { a, b } = this.state const data = { a, b } fetch(‘/Url‘, {data}).then(res => { if (res.code === 0) { this.setState({ data:res.data }) } else { message.error(res.errmsg) } }) } render() { <Children data={this.state.data}} /> } }
子组件:
componentWillReceiveProps(nextProps) { const { data } = this.state const newdata = nextProps.data.toString() if (data.toString() !== newdata) { this.setState({ data: nextProps.data, }) } }
注:react的componentWillReceiveProps周期是存在期用改变的props来判断更新自身state