0
我試圖在在[https://jscomplete.com/repl/]
https://codepen.io/stowball/post/a-dummy-s-guide-to-redux-and-thunk-in-react#understanding-redux-4
運行從教程中的代碼使用[終極版連接]上
,但執行與下面的錯誤而失敗:
ReferenceError: connect is not defined
我嘗試使用import語句在文件的頂部:
import { connect } from 'react-redux';
但它沒有幫助解決錯誤。
是否有我的方式瞭解一些錯誤jscomplete作品做任何解釋,將有助於 TIA
更新:粘貼的要求代碼:
import { connect } from 'react-redux';
class ItemList extends React.Component {
componentDidMount() {
this.props.fetchData('https://5826ed963900d612000138bd.mockapi.io/items');
}
render() {
if (this.props.hasErrored) {
return <p>Sorry! There was an error loading the items</p>;
}
if (this.props.isLoading) {
return <p>Loading…</p>;
}
return (
<ul>
{this.props.items.map((item) => (
<li key={item.id}>
{item.label}
</li>
))}
</ul>
);
}
}
const mapStateToProps = (state) => {
return {
items: state.items,
hasErrored: state.itemsHasErrored,
isLoading: state.itemsIsLoading
};
};
const mapDispatchToProps = (dispatch) => {
return {
fetchData: (url) => dispatch(itemsFetchData(url))
};
};
connect(mapStateToProps, mapDispatchToProps)(ItemList)
function itemsHasErrored(bool) {
return {
type: 'ITEMS_HAS_ERRORED',
hasErrored: bool
};
}
function itemsIsLoading(bool) {
return {
type: 'ITEMS_IS_LOADING',
isLoading: bool
};
}
function itemsFetchDataSuccess(items) {
return {
type: 'ITEMS_FETCH_DATA_SUCCESS',
items
};
}
function itemsFetchData(url) {
return (dispatch) => {
dispatch(itemsIsLoading(true));
fetch(url)
.then((response) => {
if (!response.ok) {
throw Error(response.statusText);
}
dispatch(itemsIsLoading(false));
return response;
})
.then((response) => response.json())
.then((items) => dispatch(itemsFetchDataSuccess(items)))
.catch(() => dispatch(itemsHasErrored(true)));
};
}
function itemsHasErrored(state = false, action) {
switch (action.type) {
case 'ITEMS_HAS_ERRORED':
return action.hasErrored;
default:
return state;
}
}
function itemsIsLoading(state = false, action) {
switch (action.type) {
case 'ITEMS_IS_LOADING':
return action.isLoading;
default:
return state;
}
}
function items(state = [], action) {
switch (action.type) {
case 'ITEMS_FETCH_DATA_SUCCESS':
return action.items;
default:
return state;
}
}
combineReducers({
items,
itemsHasErrored,
itemsIsLoading
});
function configureStore(initialState) {
return createStore(
rootReducer,
initialState,
applyMiddleware(thunk)
);
}
const store = configureStore(); // You can also pass in an initialState here
render(
<Provider store={store}>
<ItemList />
</Provider>,
document.getElementById('app')
);
ReactDOM.render(<ItemList/>,mountNode)
你能否提供完整的代碼和錯誤作爲問題的一部分或作爲jsFiddle? (https://jsfiddle.net/) – Madushan