我是 React 和 redux 的初学者,我有一个操作,它在 API 上发布 JSON,然后接收列表,这个操作从按钮点击调用,所有过程都很好,但是在填充数据后 ui 没有更新
行动:
import * as types from './actionTypes'
import { postMessage } from '../api/messaging'
function postToAPI(msg, dispatch) {
dispatch({ type: types.MESSAGE_POSTING });
postMessage(msg, (messages) => {
dispatch({
type: types.MESSAGE_POST_DONE,
messages: messages
});
});
}
export function postMessageAction(msg) {
return (dispatch) => {
postToAPI(msg, dispatch);
}
}
reducer :
import * as types from '../actions/actionTypes'
const initialState = {
messages: []
}
export default function messages(state = initialState, action) {
switch(action.type) {
case types.MESSAGE_POST_DONE:
return {
...state,
messages: action.messages
}
this.forceUpdate();
default:
return state;
}
}
主容器:
export default class App extends Component {
render() {
return (
<Provider store={store}>
<CounterApp />
</Provider>
);
}
}
计数器应用:
class CounterApp extends Component {
constructor(props) {
super(props);
}
render() {
const { state, actions } = this.props;
return (
<Messaging />
);
}
}
export default connect(state => ({
messages: state.default.messages.messages
}))(CounterApp);
消息:
class Messaging extends Component {
render() {
return (
<View>
<MessageList messages={this.props.messages} />
<Message />
</View>
)
}
}
export default connect(state => ({
messages: state.default.messages.messages
}))(Messaging);
消息列表:
export default class MessageList extends Component {
constructor(props) {
super(props);
}
render() {
return (
<ScrollView>
{
this.props.messages.map((item, index) => {
return (
<Text>
{ item.body }
</Text>
)
})
}
</ScrollView>
)
}
}
当消息更改时,我的 MessageList 组件不会更新。我阅读了 props 和 state 之间的区别,但我不知道如何将数据传递给 state。
更新:
我在消息连接中的状态看起来像这样为什么我使用默认值
有什么想法吗?
最佳答案
您的代码看起来很奇怪。首先,您只需要在一个组件“消息传递”中连接到 redux
import { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
const mapStateToProps = state => ({
messages: state.messages.messages
});
@connect(mapStateToProps);
class Messaging extends Component {
static propTypes = {
messages: PropTypes.object
}
render() {
const { messages } = this.props;
return (
<View>
<MessageList messages={messages} />
<Message />
</View>
)
}
}
然后像dumb组件一样使用 MessageList 来接收和呈现数据。
export default class MessageList extends Component {
constructor(props) {
super(props);
}
renderMessages(item, index) {
return <Text>{item.body}</Text>;
}
render() {
const { messages } = this.props;
return (
<ScrollView>
{messages.map((item, index) => this.renderMessages(item, index))}
</ScrollView>
);
}
}
关于javascript - UI 未更新 React 和 Redux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35790130/