【问题标题】:How to connect react and redux?react和redux怎么连接?
【发布时间】:2019-08-11 17:53:43
【问题描述】:

我是 ReactJS 的新手。我正在尝试同时使用 ReactJS 和 redux。

  1. 谁能解释一下如何将两者联系起来?

  2. 另外,在 redux reducer 中,我们通常将 intialState 设置为某个值。如何将 react 组件 state 中已经存在的值设置为 reducer 的 initialState?

下面是在我的reducer中完成的初始化,

const initialState = {
    pricing:{
        total:0
    },
    appliedPromo:false
}

下面是我在 react 组件中的状态,

state = {
    pricing: {},
    itemDetails: {},
    error: false,
    seeDetails:false,
    showPromoCode:false,
    promocodeApplied:false,
    user_discount:""
  }

我会使用 axios 更新状态,

componentDidMount() {
axios
      .get("https://purchsum-fb152.firebaseio.com/data.json")
      .then(response => {
        this.setState({ pricing: response.data.Pricing, itemDetails: response.data.itemDetails });

      })
      .catch(error => {
        this.setState({ error: true });
      });   
}

然后我将 state 连接到 props,

const mapStateToProps = (state) => {
  return{
    total: state.pricing.total,
    promoApplied: state.appliedPromo
}
}
const mapDispatchToProp = dispatch =>{
  return{
    onDiscount:()=>dispatch({type:"DISCOUNT",value:10,percentage:100})
  } 

}
export default connect(mapStateToProps,mapDispatchToProp)(PurchaseOrder); 

只有当我将 initialState 设置如下时,该应用程序才能工作,

const initialState = {
    pricing:{
        total:108.03
    },
    appliedPromo:false 
}

我不想设置它(没有硬代码)。相反,我希望 reducer 采用在组件中更新的状态值。

【问题讨论】:

标签: javascript reactjs redux


【解决方案1】:

我不想设置它(没有硬代码)。相反,我希望减速机采取 在组件中更新的状态值。

不幸的是,这不是 redux 模式。您必须设置减速器加载的初始状态 - 我不建议这可以或应该动态完成。

但是,您不能创建一个操作来在您的组件挂载时将状态设置为您想要的状态吗?

【讨论】:

    猜你喜欢
    • 2018-03-23
    • 1970-01-01
    • 2018-03-29
    • 1970-01-01
    • 1970-01-01
    • 2015-09-18
    • 1970-01-01
    • 1970-01-01
    • 2018-03-19
    相关资源
    最近更新 更多