没有redux它可以 ,这样就不会出现api连接问题
我有一个快速应用程序连接到代理我已经设法显示我的数据反应,但现在我想在redux soo中做到这一点:
有我的问题,我已经制作了所有减速器/动作,存储和组合减速器但我在页面中没有看到任何数据并且我没有'任何错误
有我的代码:
动作
export const api = ext => `http://localhost:8080/${ext}`;
//
// ─── ACTION TYPES ───────────────────────────────────────────────────────────────
//
export const GET_ADVERTS = "GET_ADVERTS";
export const GET_ADVERT = "GET_ADVERT";
//
// ─── ACTION CREATORS ────────────────────────────────────────────────────────────
//
export function getAdverts() {
return dispatch => {
fetch("adverts")
.then(res => res.json())
.then(payload => {
dispatch({ type: GET_ADVERTS, payload });
});
};
}
export function getAdvert(id) {
return dispatch => {
fetch(`adverts/${id}`)
.then(res => res.json())
.then(payload => {
dispatch({ type: GET_ADVERT, payload });
});
};
}
减速器
import { combineReducers } from "redux";
import { GET_ADVERTS, GET_ADVERT } from "../actions/actions";
const INITIAL_STATE = {
adverts: [],
advert: {}
};
function todos(state = INITIAL_STATE, action) {
switch (action.type) {
case GET_ADVERTS:
return { ...state, adverts: action.payload };
case GET_ADVERT:
return { advert: action.payload };
default:
return state;
}
}
const todoApp = combineReducers({
todos
});
export default todoApp;
index.js
//imports
const store = createStore(todoApp, applyMiddleware(thunk));
ReactDOM.render(
<Provider store={store}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>,
document.getElementById("app")
);
我的广告列表页面:
//imports..
class Adverts extends Component {
componentDidMount() {
this.props.getAdverts();
}
render() {
const { adverts = [] } = this.props;
return (
<div>
<Header />
<h1>Adverts</h1>
{adverts.map(advert => (
<li key={advert._id}>
<a href={"adverts/" + advert._id}>
{advert.name} {advert.surname}
</a>
</li>
))}
<Footer />
</div>
);
}
}
const mapStateToProps = state => ({
adverts: state.adverts
});
export default connect(
mapStateToProps,
{ getAdverts }
)(Adverts);
答案 0 :(得分:2)
我认为你的问题在这里:
function mapStateToProps(state) {
return {
**adverts: state.adverts**
};
}
如果将state.adverts 更改为 state.todos.adverts ,它应该有效:
function mapStateToProps(state) {
return {
adverts: state.todos.adverts
};
}
因为您的reducer被称为todos,并且它具有州{adverts},这就是为什么即使获得广告也无法访问广告。
您可以在此处查看工作版本:https://codesandbox.io/s/olqxm4mkpq
答案 1 :(得分:1)
问题是,当您仅使用一个减速器创建商店而不使用合并减速器时,就可以在ContainerS中直接引用它,如下所示:
const mapStateToProps = state => {
return{
*name of var*: state.adverts /*direct refers to adverts*/
}
}
但是,当使用combined-reducer时,它必须引用您要使用的精确reducer。像这样:
const mapStateToProps = state => {
return{
*name of var* : state.todos.adverts (indirect refers to adverts from combined-reducer todos)
}
}