尝试通过以下方法与JavaScript中的数组进行比较。
componentDidMount () {
this.props.onInitIngredients();
}
//Some Code...
const mapStateToProps = state => {
return {
ings: state.ingredients,
price: state.totalPrice,
error: state.error
}
};
const mapDispatchToProps = dispatch => {
return {
onIngredientAdded: (ingName) => dispatch(burgerbuilderActions.addIngredient(ingName)),
onIngredientRemoved: (ingName) => dispatch(burgerbuilderActions.removeIngredient(ingName)),
onInitIngredients: () => dispatch(burgerbuilderActions.initIngredients())
}
};
export default connect(mapStateToProps, mapDispatchToProps)(withErrorHandler(BurgerBuilder, axios));
我想让它工作,但是如果数组相同,它将返回undefined而不是true或false。
这是完整的代码:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import {Provider} from 'react-redux';
import {createStore, applyMiddleware, compose} from 'redux';
import {BrowserRouter} from 'react-router-dom';
import thunk from 'redux-thunk';
import burgerBuilderReducer from './store/reducers/burgerBuilder';
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION__ || compose;
const store = createStore(burgerBuilderReducer, composeEnhancers(
applyMiddleware(thunk)
));
const app = (
<Provider store={store}>
<BrowserRouter>
<App/>
</BrowserRouter>
</Provider>
);
使用类似方法来修复我比较数组的方式的任何帮助将不胜感激。
答案 0 :(得分:1)
以下是我用来比较 JS 中两个数组的一些方法。我通常喜欢的方法是JSON.stringify
。
不过,我觉得你的方法是最快的,只是你必须用.every()
代替forEach()
。
let stack1 = [1, 2, 3, 4];
let stack2 = [1, 2, 3, 4];
console.log('every compare:', stack1.every((v, i) => v === stack2[i]));
// or
console.log('toString compare:', stack1.toString() === stack2.toString());
// or
console.log('JSON compare:', JSON.stringify(stack1) === JSON.stringify(stack2));
// or
console.log('short compare:', stack1+'' === stack2+'');