激活其他组件中的道具后,如何重新渲染已渲染的组件

时间:2019-04-29 14:10:13

标签: react-native react-navigation

我正在React-native中建立一个具有以下条件的应用程序:

组件A:具有2个字段的搜索组件

组件B:我在此页面上单击一个按钮,出现第三个字段

该组件仅与反应导航链接

就我而言,组件B是我可以购买溢价的组件,我想在购买溢价时更新组件A。

问题:当我已经渲染了组件A,然后转到组件B时,单击按钮,组件A没有重新渲染,我该怎么办?

我正在寻找这样的东西:

class ComponentA extends PureComponent {

render() {
    if (userHasNotClickedOnComponentB) {
      return (
        <SearchForm/>
      )
    } else {
        return (
          <SearchFormPremium/>
        )
      }
  }
}

SearchForm和SearchFormPremium是两个独立的组件: 一种具有高级功能,另一种仅适用于普通用户

我已经渲染了ComponentA,然后转到ComponentB并单击按钮

class ComponentB extends PureComponent {

render() {
    return (
       <Button onClick={() => setPremium()}/>
      )
  }
}

如何重新渲染ComponentA,以便我可以更改ComponentB?

谢谢

2 个答案:

答案 0 :(得分:0)

您可能想研究使用Redux或类似的东西来保留所有组件都可以查看的集中存储。有很多Redux教程,所以我不会详细介绍,但是从本质上讲,它可以让您:

1)创建一个可从任何“连接”组件访问的数据存储

2)从任何组件调度操作以更新商店

连接组件时,连接的数据变为prop。因此,例如,如果将组件A和B连接到商店的同一部分,则组件A更新它时,组件B将自动重新渲染,因为其道具已经更改。

Redux github page

答案 1 :(得分:0)

好的,与Redux一起使用了!

只需连接两个组件。在ComponentA(必须自动更新的组件)中,使用函数componentWillReceiveProps()并在其内部刷新。

在Reducer中:

const initialState = {premium: false};

const tooglePremiumReducer = (state = initialState, action) => {
  switch (action.type) {
    case "TOOGLE_PREMIUM":
      return {
        ...state,
        premium: action.payload.premium,
      };
    default:
      return state;
  }
};

export default tooglePremiumReducer;

行动中:

export const tooglePremiumAction = (premium) => {
    return dispatch => {
      dispatch({
        type: "TOOGLE_PREMIUM",
        payload: {
          premium: premium
        }
      });
    };
  };

在ComponentB中:

// Import tooglePremiumAction
class ComponentB extends PureComponent {

render() {
    return (
       <Button onClick={() => this.props.tooglePremiumAction(true)}/>
      )
  }
}

const actions = {
  tooglePremiumAction
};

export default connect(
  actions
)(ComponentB);

在组件A中:

class ComponentA extends PureComponent {

componentWillReceiveProps(nextProps) {
    if(this.props.premium !== nextProps.premium) {
      //here refresh your component
    }
  }

render() {
    if (!this.props.premium) {
      return (
        <SearchForm/>
      )
    } else {
        return (
          <SearchFormPremium/>
        )
      }
  }
}

const mapStateToProps = state => {
  const premium = state.premium.premium
  return { premium };
};

export default connect(mapStateToProps)(ComponentA);