[英]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.