如果更改了道具,则没有更新我的组件,但是调度的动作是正确的,store is correct updated。 反应生命周期方法而无需听道具。
仅在状态更改后才重新渲染组件。 但是 shouldComponentUpdate(),getDerivedStateFromProps()和 componentDidUpdate()并没有意识到道具的改变。
如果更改了道具,如何重新渲染组件?
组件:
import React, { Component } from 'react';
import { StyleSheet, View, Text, TextInput, TouchableOpacity } from 'react-native';
export default class Main extends Component {
constructor(props) {
super(props);
this.state = {
todos: []
};
}
addTodo() {
this.props.addTodo(this.state.title)
}
render() {
return (
<View>
<Text style={style.title} >Alma</Text>
<TextInput style={style.input} placeholder="New todo title" placeholderTextColor="gray" onChangeText={(text) => this.setState({ title: text })} />
<TouchableOpacity style={{ margin: 20, backgroundColor: "lightblue", padding: 15, borderRadius: 20 }} onPress={() => this.addTodo()} >
<View>
<Text>Send</Text>
</View>
</TouchableOpacity>
{
this.props.todos.map((e, i) => {
return (
<Text style={{ textAlign: "center", fontSize: 17, margin: 10 }} key={i} >{e.title}</Text>
)
})
}
</View>
);
}
}
const style = StyleSheet.create({
title: {
textAlign: "center",
marginTop: "20%",
fontSize: 20
},
input: {
borderColor: "black",
borderWidth: 2,
borderRadius: 20,
paddingVertical: 10,
paddingHorizontal: 20,
color: "black"
}
})
import { connect } from 'react-redux'
import { addTodo } from "./reducer";
import Main from "./Main";
function mapStateToProps(state, props) {
return {
todos: state.todos
}
}
function mapDispatchToProps(dispatch, props) {
return {
addTodo: (text) => dispatch(addTodo(text))
}
}
const MainContainer = connect(
mapStateToProps,
mapDispatchToProps
)(Main)
export default MainContainer;
减速器和动作:
export default function todoReducer(state = { todos: [] }, action) {
if (action.type === 'ADD_TODO') {
let currentState = state;
currentState.todos.push(action.newTodo);
return currentState;
}
return state
}
export function addTodo(title) {
return {
type: "ADD_TODO",
newTodo: title
}
}
并存储:
import { createStore } from 'redux';
import todoReducer from "./reducer";
import { composeWithDevTools } from "redux-devtools-extension";
export default store = createStore(todoReducer,composeWithDevTools());
答案 0 :(得分:0)
您正在使用currentState.todos.push(action.newTodo)来更改化简器中的状态,它应该是一个纯函数,否则反应无法得知道具已更改。
将reducer函数更新为纯函数
export default function todoReducer(state = { todos: [] }, action) {
if (action.type === 'ADD_TODO') {
const todos = [...state.todos, action.newTodo];
return {...state, todos };
}
return state;
}