如何在React Redux中访问存储状态? [英] How do I access store state in React Redux?
本文介绍了如何在React Redux中访问存储状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我只是制作一个简单的应用程序来学习Redux的异步功能.我已经使一切正常,现在我只想在网页上显示实际状态.现在,我该如何实际使用render方法访问商店的状态?
I am just making a simple app to learn async with redux. I have gotten everything working, now I just want to display the actual state onto the web-page. Now, how do I actually access the store's state in the render method?
这是我的代码(所有内容都在一页中,因为我只是在学习):
Here is my code (everything is in one page because I'm just learning):
const initialState = {
fetching: false,
fetched: false,
items: [],
error: null
}
const reducer = (state=initialState, action) => {
switch (action.type) {
case "REQUEST_PENDING": {
return {...state, fetching: true};
}
case "REQUEST_FULFILLED": {
return {
...state,
fetching: false,
fetched: true,
items: action.payload
}
}
case "REQUEST_REJECTED": {
return {...state, fetching: false, error: action.payload}
}
default:
return state;
}
};
const middleware = applyMiddleware(promise(), thunk, logger());
const store = createStore(reducer, middleware);
store.dispatch({
type: "REQUEST",
payload: fetch('http://localhost:8000/list').then((res)=>res.json())
});
store.dispatch({
type: "REQUEST",
payload: fetch('http://localhost:8000/list').then((res)=>res.json())
});
render(
<Provider store={store}>
<div>
{ this.props.items.map((item) => <p> {item.title} </p> )}
</div>
</Provider>,
document.getElementById('app')
);
因此,在状态的render方法中,我想列出商店中的所有item.title
.
So, in the render method of the state I want to list out all the item.title
from the store.
谢谢
推荐答案
您应该创建单独的组件,该组件将侦听状态更改并在每次状态更改时进行更新:
You should create separate component, which will be listening to state changes and updating on every state change:
import store from '../reducers/store';
class Items extends Component {
constructor(props) {
super(props);
this.state = {
items: [],
};
store.subscribe(() => {
// When state will be updated(in our case, when items will be fetched),
// we will update local component state and force component to rerender
// with new data.
this.setState({
items: store.getState().items;
});
});
}
render() {
return (
<div>
{this.state.items.map((item) => <p> {item.title} </p> )}
</div>
);
}
};
render(<Items />, document.getElementById('app'));
这篇关于如何在React Redux中访问存储状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文