我知道这个错误在这个社区很常见,但我对如此愚蠢的事情感到目瞪口呆。当我试图连接mapState和mapDispatch并完成我的redux硬编码时,当我试图获取要在组件中用作道具的状态时,我得到了一个typeError
代码沙盒:https://codesandbox.io/s/flamboyant-roentgen-j4igf?file=/src/AppWrapper.js
代码本身:
index.js:
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import { createStore } from "redux";
import { reducer } from "./Redux";
import AppWrapper from "./AppWrapper";
const store = createStore(reducer);
const rootElement = document.getElementById("root");
ReactDOM.render(
<Provider store={store}>
<AppWrapper />
</Provider>,
rootElement
);
AppWrapper.js:
import { connect } from "react-redux";
import App from "./App";
import { getInputValue } from "./Redux";
const mapStateToProps = (state) => (
{
searchString: state.searchString
}
)
const mapDispatchToProps = (dispatch) => {
return {
filterByValue: (e) => {
let input = e.target.value;
dispatch(getInputValue({ value: input }));
},
triggerUserValue: () => {
dispatch({type: "TRIGGER_USER_VALUE"});
}
};
};
export default connect(mapStateToProps, mapDispatchToProps)(App);
App.js:
import "./styles.css";
import TemplateCard from "./TemplateCard";
import React from "react";
import { initialState } from "./Redux";
class App extends React.Component {
render() {
return (
<div className="App">
<input
placeholder="filter items"
onChange={this.props.filterByValue}
/>
<button onClick={this.props.triggerUserValue}> click me </button>
{initialState.productData.map((i) => {
return (
<TemplateCard
key={i.id}
title={i.title}
text={i.text}
price={i.price}
imageurl={i.imageurl}
/>
);
})}
</div>
);
}
}
export default App;
Redux.js:
export const initialState = {
searchString: "",
anotherthingy: "",
productData: [
{
id: 1,
name: "Roses",
title: "Roses",
text: "Beautiful hand picked roses fresh out of our gardins",
price: 9.99
},
{
id: 2,
name: "Dahlia",
title: "Dahlia",
text: "Beautiful hand picked Dahlia fresh out of our gardins",
price: 17.99
},
{
id: 3,
name: "Alstroemerias",
title: "Alstroemerias",
text: "Beautiful hand picked Alstroemerias fresh out of our gardins",
price: 12.99
},
{
id: 4,
name: "Calla lillies",
title: "Calla lillies",
text: "Beautiful hand picked Calla lillies fresh out of our gardins",
price: 16.99
}
]
};
export const getInputValue = (payload) => {
return {
type: "FILTER_BY_VALUE",
payload
};
};
export const reducer = (state, action) => {
switch (action.type) {
case "FILTER_BY_VALUE":
let value = action.payload.value;
console.log(value);
return { ...state, searchString: value };
case "TRIGGER_USER_VALUE":
alert(state.searchString);
return state;
default:
return state;
}
};
首先从./App
导入应用程序。您需要从./AppWrapper
导入。其次,您没有在reducer
中传递initialState
,因此状态没有初始值,因此会发生此错误。你只需要在减缩器中添加initialState
,如下所示:
export const reducer = (state = initialState, action) => {...}