我在反应组件myActions.js之外发送了这个调度:
import {SET_ORDER} from "./defaultActions";
import store from "../store";
const setOrder = value => ({type: SET_ORDER,value});
export const addToOrder = (item,type)=>{
let order = store.getState().order;//get object from store
order[type].push(JSON.parse(JSON.stringify(item)));//clone new object to push on order array
store.dispatch(setOrder(order));//dispatch new order object
};
在我的组件中,我将收到道具:
import {connect} from "react-redux";
import {addToOrder} from "myActions.js";
class Drinks extends Component{
componentDidMount(){
this.someAction();//trigger update order
}
someAction(){
addToOrder({something},'type');
}
componentWillReceiveProps(props){
//not works
//expect props.order but never appears
}
}
const stateToProps = ({order}) => ({order});
const dispatchToProps = null; //not dispatch here
const conn = connect(stateToProps,dispatchToProps);
export default conn(Drinks);
它更新了商店,但是从未调用过componentWillReceiveProps,我需要怎么做才能正确接收道具?
我的包redux库是:“react-redux”:“^ 5.0.7”,“redux”:“^ 3.7.2”,“redux-thunk”:“^ 2.3.0”我的商店工作正常在组件之间,只有当我尝试在反应组件外部调度时才会失败。
答案 0 :(得分:0)
你并没有真正克隆对象(只有项目),因此你以可变的方式更新状态,这就是从不调用componentWillReceiveProps()的原因。您的订单变量仍指向redux商店中的订单。试试这个:
export const addToOrder = (item,type) => {
let order = {...store.getState().order}; //get cloned order object from store
order[type].push(item); // push new object to cloned object
store.dispatch(setOrder(order)); //dispatch new order object
};