【发布时间】:2019-07-19 14:37:29
【问题描述】:
我正在努力学习 React 和 Redux。作为其中的一部分,我正在创建一个简单的应用程序,该应用程序从我的 REST API 中检索项目列表。为了查询这个 REST API,我使用了 Axios。目前,我不明白如何实际更新商店中的状态。 Redux 示例令人困惑。
此时,我的应用有以下内容:
/my-app
/actions
items.js
/components
items.js
App.css
App.js
index.css
index.js
store.js
/my-app/actions/items.js
import axios from 'axios';
export GET_ITEMS = 'GET_ITEMS';
export const getItems = (count) => {
axios.get('https://my-app.com/items')
.then(function(response) {
console.log(response.results);
// need to set "response.results" to the value in the store
}
};
/components/items.js
import React from 'react';
import { getItems } from '../actions/items';
class Items extends React.Component {
constructor(props) {
super(props);
this.state = {
items: []
}
}
onButtonClick = () => {
getItems(5);
}
render() {
return {
<div>
<button type="button" onClick={this.onButtonClick}>Load Items</button>
<br />
{this.state.items.map((item) => {
<div>{item.name}</div>
))}
</div>
}
}
}
App.js
import React from 'react';
import Items from './components/items';
function App() {
return {
<div>
<Items></Items>
</div>
};
}
export default App;
/store.js
import { createStore } from 'redux';
import { GET_ITEMS } from './actions/items';
let initialState = {
items: [
{
id:1,
name:'Item A',
description: 'This is a pre-populated item for testing purposes.'
}
]
}
function itemsReducer(state, action) {
switch (action.type) {
case GET_ITEMS:
break;
default:
return state;
}
}
let store = createStore(itemsReducer, initialState);
export default store;
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import store from './store';
import App from './App';
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
当我运行它时,我看到一个带有按钮的屏幕。我可以单击按钮,但是,我没有看到屏幕上显示的项目。如果我查看控制台窗口,我可以看到通过 console.log 语句打印的项目。
如何获取从 REST API 返回的项目并 a) 在 store 中设置这些项目并 b) 在我的组件中使用商店项目?
非常感谢您的帮助! Redux 一直是个挑战。
【问题讨论】:
标签: javascript reactjs redux