[英]React Native components not re-render if props changed
如果 props 更改,则不更新我的组件,但调度的操作是正确的并且store 是正确的更新。 React 生命周期方法没有监听 props。
只有在状态改变时才重新渲染组件。 但是shouldComponentUpdate()、getDerivedStateFromProps()和componentDidUpdate()并没有意识到 props 发生了变化。
如果 props 改变,如何重新渲染组件?
成分:
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());
您正在使用 currentState.todos.push(action.newTodo) 改变 reducer 中的状态,它应该是一个纯函数,否则 react 无法知道 props 发生了变化。
将您的 reducer 函数更新为纯函数
export default function todoReducer(state = { todos: [] }, action) {
if (action.type === 'ADD_TODO') {
const todos = [...state.todos, action.newTodo];
return {...state, todos };
}
return state;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.